我想要一个绘图,其中一个绘图中有来自两个不同数据帧的两个y轴。
到目前为止,我尝试更改一个数据框的两个y轴版本,但失败了。
import pandas as pd
import matplotlib.pyplot as plt
plt.close("all")
df1 = pd.DataFrame({"x1": [1,2 ,3 ,4 ],
"y1_1": [555,525,532,585],
"y1_2": [50,48,49,51]})
df2 = pd.DataFrame({"x2": [1, 2, 3,4],
"y2_1": [557,522,575,590],
"y2_2": [47,49,50,53]})
ax1 = df1.plot(x="x1", y="y1_1", legend=False)
ax2 = ax1.twinx()
df1.plot(x="x1", y="y1_2", ax=ax2, legend=False, color="r")
ax3 = df2.plot(x="x2", y="y2_1", legend=False)
ax4 = ax1.twinx()
df2.plot(x="x2", y="y2_2", ax=ax4, legend=False, color="r")
plt.grid(True)
ax1.figure.legend()
plt.show()
答案 0 :(得分:1)
这是您想要的吗?
ax1 = df1.plot(x="x1", y="y1_1", legend=False)
ax2=ax1.twinx()
df1.plot(x="x1", y="y1_2", ax=ax2, legend=False, color="r")
df2.plot(x="x2", y="y2_1", ax=ax1, legend=False)
df2.plot(x="x2", y="y2_2", ax=ax2, legend=False, color="r")
给出:
或者,您可以预定义ax1
和ax2
,然后将它们传递给plot
函数:
fig, ax1 = plt.subplots()
ax2=ax1.twinx()
df1.plot(x="x1", y= ["y1_1"], ax=ax1, legend=False)
df1.plot(x="x1", y="y1_2", ax=ax2, legend=False, color="r")
df2.plot(x="x2", y="y2_1", ax=ax1, legend=False)
df2.plot(x="x2", y="y2_2", ax=ax2, legend=False, color="r")