Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách chú thích cuối đường (annotate end of lines) bằng Python và Matplotlib?

Để chú thích cuối các đường trong Python và Matplotlib:

  • Thiết lập kích thước hình và điều chỉnh khoảng đệm subplot.
  • Khởi tạo biến rows cho số hàng dữ liệu.
  • Tạo DataFrame pandas dạng bảng chữ nhật.
  • Tính cumsum (tổng tích lũy) của DataFrame.
  • Vẽ DataFrame bằng plot().
  • Duyệt line và name để chú thích cuối đường.
  • Dùng annotate() với tên cột, tọa độ xy, màu đường, cỡ chữ, v.v.
  • Đặt legend.
  • Hiển thị hình bằng show().

Ví dụ

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
rows = 75
df = pd.DataFrame(np.random.randint(-5, 5, size=(rows, 3)), columns=['A', 'B', 'C'])
df = df.cumsum()
ax = df.plot()
for line, name in zip(ax.lines, df.columns):
    y = line.get_ydata()[-1]
    ax.annotate(name, xy=(1, y), xytext=(6, 0),
                color=line.get_color(), xycoords=ax.get_yaxis_transform(),
                textcoords="offset points", size=14, va="center")
plt.legend(loc='lower left')
plt.show()

Kết quả

Cách chú thích cuối đường (annotate end of lines) bằng Python và Matplotlib?