如何在同一图中绘制两个Pandas时间序列,包括图例和次要y轴?

22
我想在同一张图上绘制两个时间序列,使用相同的x轴和次要y轴。我已经设法实现了这一点,但是两个图例重叠在一起,无法为x轴和次要y轴提供标签。我尝试将两个图例放置在左上角和右上角,但仍然不起作用。
代码:
plt.figure(figsize=(12,5))

# Number of request every 10 minutes
log_10minutely_count_Series = log_df['IP'].resample('10min').count()
log_10minutely_count_Series.name="Count"
log_10minutely_count_Series.plot(color='blue', grid=True)
plt.legend(loc='upper left')
plt.xlabel('Number of request ever 10 minute')

# Sum of response size over each 10 minute
log_10minutely_sum_Series = log_df['Bytes'].resample('10min').sum()
log_10minutely_sum_Series.name = 'Sum'
log_10minutely_sum_Series.plot(color='red',grid=True, secondary_y=True)
plt.legend(loc='upper right')
plt.show()

输入图片说明

提前感谢。

2个回答

28

以下解决方案适用于我。第一个将两行放在一个图例中,第二个将线条分成两个图例,与您上面尝试的类似。

这是我的数据框:

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))

一个传奇解决方案,鸣谢这篇StackOverflow帖子

plt.figure(figsize=(12,5))
plt.xlabel('Number of requests every 10 minutes')

ax1 = df.A.plot(color='blue', grid=True, label='Count')
ax2 = df.B.plot(color='red', grid=True, 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()

一个图例的 matplotlib 绘图

拆分图例的解决方法

plt.figure(figsize=(12,5))
plt.xlabel('Number of requests every 10 minutes')

ax1 = df.A.plot(color='blue', grid=True, label='Count')
ax2 = df.B.plot(color='red', grid=True, secondary_y=True, label='Sum')

ax1.legend(loc=1)
ax2.legend(loc=2)

plt.show()

分离 Matplotlib 图例的图


对于分离图例的绘制,最好交换图例的“loc”位置,因为loc=1是指右上角,而右y轴是次要y轴,而loc=2是指左上角(靠近主要y轴)。请参阅图例文档:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html - Benjamin Wang

10

它可以非常简单,例如:

df.loc[:,['A','B']].plot(secondary_y=['B'], mark_right=False, figsize = (20,5), grid=True)

mark_right=False的意思是'B'标签位于左轴。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接