如何在 Matplotlib 中在同一张图上绘制两个带有图例和辅助 Y 轴的 Pandas 时间序列?
matplotlibpythondata visualization更新于 2025/6/8 7:08:17
要在同一张图上绘制两个带有图例和辅助 Y 轴的 Pandas 时间序列,我们可以采取以下步骤 −
设置图形大小并调整子图之间和周围的填充。
创建一个带有轴标签(包括时间序列)的一维 ndarray。
创建一个带有一些列列表的数据框。
使用数据框 plot() 方法绘制列 A 和 B。
使用 get_legend_handles_labels() 返回图例的句柄和标签方法。
使用 legend() 方法在图形上放置图例。
要显示图形,请使用 show() 方法。
示例
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
ts = pd.Series(np.random.randn(10), index=pd.date_range('2021-04-10', periods=10))
df = pd.DataFrame(np.random.randn(10, 4), index=ts.index, columns=list('ABCD'))
ax1 = df.A.plot(color='red', label='Count')
ax2 = df.B.plot(color='yellow', secondary_y=True, label='Sum')
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
plt.legend(h1+h2, l1+l2, loc=2)
plt.show()
输出

相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

