如何在Matplotlib中绘制两个Pandas时间序列的相同图,并在该图中添加图例和次级Y轴?

如何在Matplotlib中绘制两个Pandas时间序列的相同图,并在该图中添加图例和次级Y轴?

要在带有图例和次级Y轴的相同绘图中绘制两个Pandas时间序列,可以执行以下步骤 –

  • 设置图形大小并调整子图之间和周围的填充。

  • 创建一个带有轴标签(包括时间序列)的一维 ndarray

  • 使用一些列列表创建一个数据帧。

  • 使用数据帧plot()方法绘制列 AB

  • 使用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='计数')
ax2 = df.B.plot(color='yellow', secondary_y=True, label='总和')

h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()

plt.legend(h1+h2, l1+l2, loc=2)

plt.show()

输出

如何在Matplotlib中绘制两个Pandas时间序列的相同图,并在该图中添加图例和次级Y轴?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程