Hãy tải một số thư viện. Mô -đun
# Ensures reproducibility of random numbers
rng = np.random.default_rng[1234]
0 cung cấp các lớp để thao tác ngày và thời gian và đi kèm với thư viện Python tiêu chuẩn.import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime, timedelta
# Ensures reproducibility of random numbers
rng = np.random.default_rng[1234]
Hãy xem xét một bộ dữ liệu với 3 biến:
- ngày
- Nhiệt độ: Sê -ri đầu tiên hiển thị. Dao động từ 0 đến 10.: the first series to display. Ranges from 0 to 10.
- Giá: Sê -ri thứ hai để hiển thị. Dao động từ 20 đến 120.: the second series to display. Ranges from 20 to 120.
# timedelta[i] adds "i" days to the 1st of January of 2019
date = [datetime[2019, 1, 1] + timedelta[i] for i in range[100]]
temperature = np.arange[100] ** 2.5 / 10000 + rng.uniform[size=100]
price = np.arange[120, 20, -1] ** 1.5 / 10 + rng.uniform[size=100]
Người ta có thể dễ dàng xây dựng các biểu đồ 2 dòng để nghiên cứu sự phát triển của 2 chuỗi đó bằng cách sử dụng mã bên dưới.
fig, axes = plt.subplots[1, 2, figsize=[12, 5]]
axes[0].plot[date, temperature]
axes[1].plot[date, price];
Nhưng ngay cả khi không được chứng minh mạnh mẽ, đôi khi người ta muốn hiển thị cả hai chuỗi trên cùng một biểu đồ, do đó cần trục Y thứ hai.
Tạo một trục sinh đôi mới chia sẻ trục X với # Ensures reproducibility of random numbers
rng = np.random.default_rng[1234]
1: Ý tưởng
# Ensures reproducibility of random numbers
rng = np.random.default_rng[1234]
fig, ax1 = plt.subplots[figsize=[9, 6]]
# Instantiate a second axes that shares the same x-axis
ax2 = ax1.twinx[]
ax2.set_ylim[4, 20];
Như có thể thấy ở trên, trục Y ở bên trái đi từ 0 đến 1, trong khi trục Y ở bên phải đi từ 4 đến 20. Các giới hạn này được điều chỉnh tự động khi chúng ta truyền dữ liệu.
Lưu ý rằng vì cả hai trục y đều độc lập, bạn có thể dễ dàng đặt bất kỳ giới hạn tùy chỉnh nào trên trục Y thứ cấp.
Hiển thị 2 loạt trên cùng một biểu đồ dòng nhờ # Ensures reproducibility of random numbers
rng = np.random.default_rng[1234]
1
# Ensures reproducibility of random numbers
rng = np.random.default_rng[1234]
# Ensures reproducibility of random numbers
rng = np.random.default_rng[1234]
1 Trả về một thể hiện trục có thể được sử dụng giống như bất kỳ trục matplotlib nào khác. Tính đặc biệt duy nhất của trục mới này là nó chia sẻ trục ngang với cái đầu tiên.fig, ax1 = plt.subplots[figsize=[8, 8]]
ax2 = ax1.twinx[]
ax1.plot[date, temperature]
ax2.plot[date, price];
Tùy chỉnh trục y kép với matplotlib
Hãy thêm một số chi tiết để làm cho biểu đồ trông đẹp hơn:
- Sử dụng màu sắc đặc biệt cho các đường và nhãn.
- Làm cho dòng dày hơn.
- Thêm nhãn trục.
- Thêm tiêu đề
- Định dạng nhãn ngày trên trục ngang.
COLOR_TEMPERATURE = "#69b3a2"
COLOR_PRICE = "#3399e6"
fig, ax1 = plt.subplots[figsize=[8, 8]]
ax2 = ax1.twinx[]
ax1.plot[date, temperature, color=COLOR_TEMPERATURE, lw=3]
ax2.plot[date, price, color=COLOR_PRICE, lw=4]
ax1.set_xlabel["Date"]
ax1.set_ylabel["Temperature [Celsius °]", color=COLOR_TEMPERATURE, fontsize=14]
ax1.tick_params[axis="y", labelcolor=COLOR_TEMPERATURE]
ax2.set_ylabel["Price [$]", color=COLOR_PRICE, fontsize=14]
ax2.tick_params[axis="y", labelcolor=COLOR_PRICE]
fig.suptitle["Temperature down, price up", fontsize=20]
fig.autofmt_xdate[]
Barplot với biểu đồ dòng chồng chéo
Cũng có thể sử dụng các thủ thuật tương tự với các loại lô khác. Dưới đây là một ví dụ hiển thị một biểu đồ dòng trên đỉnh của một chấu.
fig, ax1 = plt.subplots[figsize=[8, 8]]
ax2 = ax1.twinx[]
ax1.bar[date, temperature, color=COLOR_TEMPERATURE, edgecolor="black", alpha=0.4, width=1.0]
ax2.plot[date, price, color=COLOR_PRICE, lw=4]
ax1.set_xlabel["Date"]
ax1.set_ylabel["Temperature [Celsius °]", color=COLOR_TEMPERATURE, fontsize=14]
ax1.tick_params[axis="y", labelcolor=COLOR_TEMPERATURE]
ax2.set_ylabel["Price [$]", color=COLOR_PRICE, fontsize=14]
ax2.tick_params[axis="y", labelcolor=COLOR_PRICE]
fig.autofmt_xdate[]
fig.suptitle["Temperature down, price up", fontsize=20];
Sau đây là một mẹo để đặt độ trong suốt chỉ trên màu của điền và không ở cạnh:
from matplotlib import colors
# Convert color to RGBA
color = list[colors.to_rgba[COLOR_TEMPERATURE]]
# Set opacity level in the A channel to something smaller than 1 [but larger than 0]
color[3] = 0.4
fig, ax1 = plt.subplots[figsize=[8, 8]]
ax2 = ax1.twinx[]
ax1.bar[date, temperature, color=color, edgecolor="black", width=1.0]
ax2.plot[date, price, color=COLOR_PRICE, lw=4]
ax1.set_xlabel["Date"]
ax1.set_ylabel["Temperature [Celsius °]", color=COLOR_TEMPERATURE, fontsize=14]
ax1.tick_params[axis="y", labelcolor=COLOR_TEMPERATURE]
ax2.set_ylabel["Price [$]", color=COLOR_PRICE, fontsize=14]
ax2.tick_params[axis="y", labelcolor=COLOR_PRICE]
fig.autofmt_xdate[]
fig.suptitle["Temperature down, price up", fontsize=20];