如何在带有传说和次要Y轴的同一地块上绘制两个 pandas 时间序列? [英] How to plot two pandas time series on same plot with legends and secondary y-axis?

查看:91
本文介绍了如何在带有传说和次要Y轴的同一地块上绘制两个 pandas 时间序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在同一图上用相同的x轴和次要y轴绘制两个时间序列.我已经以某种方式实现了这一点,但是两个图例重叠并且无法为x轴和辅助y轴添加标签.我尝试将两个图例放在左上角和右上角,但仍然无法正常工作.

I want to plot two time series on the same plot with same x-axis and secondary y-axis. I have somehow achieved this, but two legends are overlapping and is unable to give label to x-axis and secondary y-axis.I tried putting two legend at upper-left and upper-right, but it is still not working.

代码:

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()

预先感谢

推荐答案

以下解决方案对我有用.第一种将两条线都放在一个图例中,第二种将线分成两个图例,类似于您在上方所做的尝试.

The following solutions work for me. The first places both lines in one legend, the second splits lines into two legends, similar to what you are trying above.

这是我的数据框

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帖子

One legend solution, credit to this StackOverflow post

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()

拆分图例解决方案

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()

这篇关于如何在带有传说和次要Y轴的同一地块上绘制两个 pandas 时间序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆