无法控制 df.plot() 上第二个 y 轴的比例

Unable to control scale of second y-axis on df.plot()

我正在尝试使用 secondary_y 绘制 3 个系列,左侧 y 轴上有 2 个,右侧有 1 个,但我不清楚如何像我那样定义右侧的 y 轴刻度在左边 ylim=().

我看过这个post:Interact directly with axes

…但是一旦我有:

import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.randn(10,3))

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.plot(df.index,df.iloc[:,[0,2]])
ax2.plot(df.index, df.iloc[:,2])

plt.show() 根本不产生任何东西。我正在使用:

我发现这些链接很有帮助:

tcaswell, working directly with axes

matplotlib.axes documentation

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10,3))
print (df)
fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.plot(df.index,df.iloc[:,[0,2]])
ax2.plot(df.index, df.iloc[:,2])

plt.show()

你需要在合适的斧头上使用set_ylim

例如:

ax2 = ax1.twinx()
ax2.set_ylim(bottom=-10, top=10)

此外,查看您的代码,您似乎错误地指定了 iloc 列。尝试:

ax1.plot(df.index, df.iloc[:, :2])  # Columns 0 and 1.
ax2.plot(df.index, df.iloc[:, 2])   # Column 2.

你可以不直接调用 ax.twinx():

#Plot the first series on the LH y-axis
ax1 = df.plot('x_column','y1_column')

#Add the second series plot, and grab the RH axis
ax2 = df.plot('x_column','y2_column',ax=ax1)
ax2.set_ylim(0,10)

注意:仅在 Pandas 19.2

中测试