Python 如何使用图例和辅助 y 轴在同一图上绘制两个熊猫时间序列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46011940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to plot two pandas time series on same plot with legends and secondary y-axis?
提问by Om Prakash
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.
我想用相同的 x 轴和辅助 y 轴在同一个图上绘制两个时间序列。我以某种方式实现了这一点,但是两个图例重叠并且无法为 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
提前致谢
回答by Josh
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 thisStackOverflow 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()
回答by Sarah
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”标签在左轴上。