gpt4 book ai didi

python - 如何在具有图例和次要 y 轴的同一图上绘制两个 Pandas 时间序列?

转载 作者:太空狗 更新时间:2023-10-29 18:01:20 25 4
gpt4 key购买 nike

我想在具有相同 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()

enter image description here

提前致谢

最佳答案

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

这是我的数据框

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

一个图例解决方案,归功于 this 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()

One legend matplotlib plot

拆分图例解决方案

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

Split legend matplotlib plot

关于python - 如何在具有图例和次要 y 轴的同一图上绘制两个 Pandas 时间序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46011940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com