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

Cách đặt bảng lên biểu đồ trong Matplotlib

Các bước

  • Sử dụng phương thức subplots() tạo hình và tập subplots với kích thước (7, 7).
  • Tạo DataFrame với hai khóa time và speed.
  • Lấy kích thước mảng.
  • Thêm bảng vào trục hiện tại bằng phương thức table.
  • Thu nhỏ cỡ chữ cho vừa ô.
  • Đặt cỡ chữ cho bảng.
  • Đặt màu nền, màu viền, màu chữ bằng cách lặp qua bảng matplotlib.
  • Lưu và hiển thị hình.

Ví dụ

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
df = pd.DataFrame(dict(time=list(pd.date_range("2021-01-01 12:00:00", periods=10)), speed=np.linspace(1, 10, 10)))
size = (np.array(df.shape[::-1]) + np.array([0, 1])) * np.array([3.0, 6.0])
mpl_table = ax.table(cellText=df.values, bbox=[0, 0, 1, 1], colLabels=df.columns)
mpl_table.auto_set_font_size(False)
mpl_table.set_fontsize(12)
for k, cell in mpl_table._cells.items():
    cell.set_edgecolor('black')
    if k[0] == 0 or k[1] < 0:
        cell.set_text_props(weight='bold', color='w')
        cell.set_facecolor('red')
    else:
        cell.set_facecolor(['green', 'yellow'][k[0] % 2])
plt.show()

Kết quả

Cách đặt bảng lên biểu đồ trong Matplotlib