【发布时间】:2021-11-09 20:38:18
【问题描述】:
有人可以告诉我如何绘制多个 Y 轴图吗?
这是下面一些虚构的数据,我怎么能把Temperature放在自己的Y轴上,Pressure放在自己的Y轴上,然后把Value1和Value2放在自己的Y轴上相同 Y 轴。我正在尝试使用相同的外观和感觉of this SO post answer。感谢您提供任何提示,我不明白 ax3 = ax.twinx() 过程,就像我需要为我需要的每个单独的 Y 轴图定义一个 ax.twinx() 吗?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
rows,cols = 8760,4
data = np.random.rand(rows,cols)
tidx = pd.date_range('2019-01-01', periods=rows, freq='H')
df = pd.DataFrame(data, columns=['Temperature','Value1','Pressure','Value2'], index=tidx)
# using subplots() function
fig, ax = plt.subplots(figsize=(25,8))
plt.title('Multy Y Plot')
ax2 = ax.twinx()
ax3 = ax.twinx()
ax4 = ax.twinx()
plot1, = ax.plot(df.index, df.Temperature)
plot2, = ax2.plot(df.index, df.Value1, color = 'r')
plot3, = ax3.plot(df.index, df.Pressure, color = 'g')
plot4, = ax4.plot(df.index, df.Value2, color = 'b')
ax.set_xlabel('Date')
ax.set_ylabel('Temperature')
ax2.set_ylabel('Value1')
ax3.set_ylabel('Pressure')
ax4.set_ylabel('Value2')
plt.legend([plot1,plot2,plot3,plot4],list(df.columns))
# defining display layout
plt.tight_layout()
# show plot
plt.show()
这将输出在同一侧混乱的所有内容,没有单独的 Y 轴用于压力、Value1 和 Value2。
【问题讨论】:
标签: python pandas matplotlib