[英]How to plot two pandas time series on same plot with legends and secondary y-axis?
I want to plot two time series on the same plot with same x-axis and secondary y-axis. 我想在相同的图上用相同的x轴和次y轴绘制两个时间序列。 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. 我已经以某种方式实现了这一点,但是两个传说重叠并且无法给x轴和次y轴赋予标签。我尝试在左上角和右上角放置两个图例,但它仍然不起作用。
Code: 码:
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()
Thanks in advance 提前致谢
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. 第一个将两条线放在一个图例中,第二条线将两条线分成两个图例,类似于您在上面尝试的内容。
Here is my dataframe 这是我的数据帧
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'))
One legend solution, credit to this StackOverflow post 一个传奇解决方案,归功于这个 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()
Split legend solution 拆分传奇解决方案
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()
It can be as simple as: 它可以很简单:
df.loc[:,['A','B']].plot(secondary_y=['B'], mark_right=False, figsize = (20,5), grid=True)
mark_right=False means that 'B' label is on the left axis. mark_right = False表示'B'标签位于左轴上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.