Pandas: 我怎样才能用单独的 y 轴绘图,但仍然控制顺序?
Pandas: How can I plot with separate y-axis, but still control the order?
我正在尝试在一个图中绘制多个时间序列。尺度不同,所以它们需要单独的 y 轴,我希望特定时间序列的 y 轴在右边。我也希望那个时间序列落后于其他时间序列。但我发现当我使用 secondary_y=True
时,这个时间序列总是被带到前面,即使绘制它的代码出现在其他代码之前。使用 secondary_y=True
时如何控制绘图的顺序(或者有替代方法)?
此外,当我使用 secondary_y=True
时,左侧的 y 轴不再适应适当的值。这个有固定的吗?
# imports
import numpy as np
import matplotlib.pyplot as plt
# dummy data
lenx = 1000
x = range(lenx)
np.random.seed(4)
y1 = np.random.randn(lenx)
y1 = pd.Series(y1, index=x)
y2 = 50.0 + y1.cumsum()
# plot time series.
# use ax to make Pandas plot them in the same plot.
ax = y2.plot.area(secondary_y=True)
y1.plot(ax=ax)
所以我想要的是在绿色时间序列后面绘制蓝色区域,并让左侧 y 轴为绿色时间序列取适当的值:
https://i.stack.imgur.com/6QzPV.png
也许像下面这样使用 matplotlib.axes.Axes.twinx
instead of using secondary_y
, and then following the approach in 将孪生轴移动到背景:
# plot time series.
fig, ax = plt.subplots()
y1.plot(ax=ax, color='green')
ax.set_zorder(10)
ax.patch.set_visible(False)
ax1 = ax.twinx()
y2.plot.area(ax=ax1, color='blue')
我正在尝试在一个图中绘制多个时间序列。尺度不同,所以它们需要单独的 y 轴,我希望特定时间序列的 y 轴在右边。我也希望那个时间序列落后于其他时间序列。但我发现当我使用 secondary_y=True
时,这个时间序列总是被带到前面,即使绘制它的代码出现在其他代码之前。使用 secondary_y=True
时如何控制绘图的顺序(或者有替代方法)?
此外,当我使用 secondary_y=True
时,左侧的 y 轴不再适应适当的值。这个有固定的吗?
# imports
import numpy as np
import matplotlib.pyplot as plt
# dummy data
lenx = 1000
x = range(lenx)
np.random.seed(4)
y1 = np.random.randn(lenx)
y1 = pd.Series(y1, index=x)
y2 = 50.0 + y1.cumsum()
# plot time series.
# use ax to make Pandas plot them in the same plot.
ax = y2.plot.area(secondary_y=True)
y1.plot(ax=ax)
所以我想要的是在绿色时间序列后面绘制蓝色区域,并让左侧 y 轴为绿色时间序列取适当的值:
https://i.stack.imgur.com/6QzPV.png
也许像下面这样使用 matplotlib.axes.Axes.twinx
instead of using secondary_y
, and then following the approach in
# plot time series.
fig, ax = plt.subplots()
y1.plot(ax=ax, color='green')
ax.set_zorder(10)
ax.patch.set_visible(False)
ax1 = ax.twinx()
y2.plot.area(ax=ax1, color='blue')