如何在与图例和次要y轴相同的情节上绘制两个大熊猫时间序列?

Om *_*ash 13 python matplotlib pandas

我想在相同的图上用相同的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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

提前致谢

Jos*_*osh 17

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

这是我的数据帧

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'))
Run Code Online (Sandbox Code Playgroud)

一个传奇解决方案,归功于这个 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()
Run Code Online (Sandbox Code Playgroud)

一个传奇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()
Run Code Online (Sandbox Code Playgroud)

拆分传奇matplotlib图


Sar*_*rah 5

它可以很简单:

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

mark_right=False 表示“B”标签在左轴上。