为索引为字符串的pandas/matplotlib设置xlim

3 投票
2 回答
7405 浏览
提问于 2025-04-18 11:25

我有一个 pandas 数据框,它的索引是字符串类型的。现在我想设置 x 轴的范围,但我的数据框索引是对象类型的。我试过在数据的开头和结尾各加上两年,里面全是 np.nan,但这样并没有成功。

这是我的数据框:

数据框

索引的数据类型是对象。

df.index
Out[52]: Index(['2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012'], dtype='object')

这是我的图表:

Matplotlib 图表

我希望在 x 轴上留出一些额外的空间,这样第一个和最后一个年份的值能更清楚地显示出来。我该怎么做呢?

编辑:

这是一个使用对象而不是日期对象作为索引的简单示例。

ipython notebook

2 个回答

5

使用 set_xlim 可以调整图表的横坐标范围,+1 表示向右移动1个单位,-1 则是向左移动1个单位。在下面的例子中,我把图表的范围向两边各扩展了0.5个月:

df=pd.DataFrame({'A': range(10), 'B': range(1, 11), 'C': range(2,12)})
df.index=pd.date_range('2001/01/01', periods=10, freq='M')
ax=df.plot(kind='line')
ax.set_xlim(np.array([-0.5, 0.5])+ax.get_xlim())

enter image description here

另外,如果想要每年都有一个 xticklabel(横坐标标签),而不是默认的每两年一个,可以使用 pandas 来实现:

ax=df.plot(kind='line', xticks=df.index)
ax.set_xticklabels(df.index.map(lambda x: datetime.datetime.strftime(x, '%Y')))

enter image description here

3
from __future__ import print_function
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

df = pd.DataFrame({'Foo': pd.Series([2,3,4], index=['2002', '2003', '2004'])})
fig, ax = plt.subplots()

df.plot(ax=ax)

这段代码会生成一个图表。如果想看看x轴的刻度标签是怎么处理的,可以查看:

# note this is an AutoLocator
print(ax.xaxis.get_major_locator())
# note this is a FixedFormatter
print(ax.xaxis.get_major_formatter())
# these are the ticks that are used
ff = ax.xaxis.get_major_formatter()
print(ff.seq)

这意味着如果你在图表上移动,刻度标签会保持不变,但位置会随机变化。这和改变x轴的范围是一个问题,因为在pandas最开始设置图表时,刻度标签和数据是完全分开的。

解决这个问题有一种(比较啰嗦的)方法:

ax.xaxis.set_major_locator(mticker.FixedLocator(np.arange(len(df))))
ax.xaxis.set_major_formatter(mticker.FixedFormatter(df.index))


# note this is a FixedLocator
print(ax.xaxis.get_major_locator())
# note this is a FixedFormatter
print(ax.xaxis.get_major_formatter())

无论你把索引设置成什么(字符串或日期),这个方法都能正常工作。

我在pandas上创建了一个问题,链接是 https://github.com/pydata/pandas/issues/7612

撰写回答