x 轴被 pandas.plot(...) 意外反转

use*_*097 1 python matplotlib pandas

使用 pandas 将一系列数据与另一系列数据进行比较时,X 轴意外地自动反转。请看下面我的代码。如何确保x轴始终指向右侧?x 轴的这种自动反转是 pandas 的预期行为吗?可以禁用吗?

让我在下面解释一下我的例子。创建了三个图。我预计每一个都显示出向右上升的近 45 度线。然而,其中一些有 45 度线向右倾斜,因为它的 x 轴自动反转。看来 x 轴是否反转取决于要绘制的值。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df2 = pd.DataFrame(np.random.randn(10, 3), columns=["a", "b", "c"])
df3 = df2*1.1

df3.rename(columns={"a": "a*1.1", "b": "b*1.1", "c": "c*1.1"}, inplace=True)
df23 = df2.join(df3)

fig, ax_list = plt.subplots(1,3)

ax=ax_list[0]
df23[["a", "a*1.1"]].plot(ax=ax, x="a")
ax.axis('equal')
ax.set_title("(x,y)=(a,a*1.1)")
print ax.get_xlim()  ## Added for clarity

ax=ax_list[1]
df23[["b", "b*1.1"]].plot(ax=ax, x="b")
ax.axis('equal')
ax.set_title("(x,y)=(b,b*1.1)")
print ax.get_xlim()  ## Added for clarity  

ax=ax_list[2]
df23[["c", "c*1.1"]].plot(ax=ax, x="c")
ax.axis('equal')
ax.set_title("(x,y)=(c,c*1.1)")
print ax.get_xlim()  ## Added for clarity
Run Code Online (Sandbox Code Playgroud)

创建情节

use*_*097 5

我在pandas 的问题跟踪器上问了这个问题,并得到了答案。

daraframe.plot(..) 的设计使得

  • 点的 x 坐标是根据 x 参数指定的列的索引(即行号)确定的。
  • 点的 y 坐标是 y 参数指定的列的值。

对于散点图,我认为上面的设计不合适。我能想到的唯一解决方案是直接使用 plt.plot 。

cphlewis 的解决方法也很有用。