我正在尝试将 pandas 数据框绘制为条形图和线图。
这个 MWE 总结了我所关注的内容:
import pandas as pd
import matplotlib.pyplot as plt
test_df = pd.DataFrame(np.random.rand(20,2), columns = ['A', 'B'])
test_df['A'] = test_df['A'].cumsum()
test_df['B'] = test_df['B'].cumsum()
test_df.index += 1
然后我绘制条形图:
ax = test_df.plot(kind='bar', colors=['red', 'blue'], figsize = (13.5,6))
然后,我以某种方式进一步操作数据,形成一个上限,将其绘制为针对条形的线:
test_df['C'] = test_df.index
test_df['Upper'] = 4 * (test_df['C']/5)**0.5
test_df['Upper'].plot()
xlim
被更改,线图也不会像我从 pandas df 索引中期望的那样从索引 1 开始。如何解决以上问题?
您的示例中发生了两件事。
1) 当您使用
'A'
的 'B'
方法制作 plot(kind='bar')
和 test_df
的条形图时,pandas 会创建一个绘图,其中 test_df.index
中的值用作'A'
和 'B'
列中的对应对。我假设 pandas 这样做是因为条形图通常与 x 轴上的分类变量一起使用。这可以通过以下代码来说明:
>>> test_df.index = [1, 2, 3, 4, 100, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> ax = test_df[['A', 'B']].plot(kind='bar', color=['red', 'blue'])
产生:
这意味着第一个图中的 x 轴刻度标签不是绘制值的实际 x 值。相反,
1
实际上位于 x = 0,因为它是索引的第一个值,而 20
位于 x = 19。您可以通过检查 x 轴限制来推断这一点:
>>> ax.get_xlim()
(-0.5, 19.5)
2) 调用
test_df['Upper'].plot()
(不带 kind='bar'
)绘制 'Upper'
列中的值,并使用 test_df.index
作为 x 坐标。此调用使用当前轴,并且看起来它还更改了 x 轴限制以适应最新绘制的数据,其 x 值为 1 到 20。如果您检查第二个图上的轴限制,它们将是 (1.0, 20.0)
.
为了解决这一切,我建议在绘制数据之前不要增加索引并将其保持在 0-19 之间。这样你就知道所有的 x 坐标都是相同的。然后在绘制它们之后,您可以使用
ax.set_xticklabels(['your', 'x', 'tick', 'labels'])
显式设置 x 刻度标签。
可能有一个
kwarg
您可以添加到 df.plot(kind='bar', ...)
来设置绘制条形的 x 坐标,但我目前似乎找不到它。
您可以使用以下代码将折线图与条形图对齐:
ax.set_xlim(ax.get_xlim()[0]-0.5, ax.get_xlim()[1]+0.5)