【问题标题】:Set xlim for pandas/matplotlib where index is string为索引为字符串的 pandas/matplotlib 设置 xlim
【发布时间】:2014-06-28 15:33:08
【问题描述】:

我有一个使用字符串作为索引的 pandas 数据框。当我的数据框索引是对象类型时,如何为 x 轴设置 xlim?我尝试在最后添加两年,在所有数据集都是 np.nan 的开头添加一年,但这没有用。

这是数据框

index的数据类型是object

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

这是剧情

所以我想在 x 轴上有一些额外的空间,这样拳头和去年的值就更清晰了。我能做什么?

编辑

这是一个使用对象而不是日期对象作为索引的最小示例

ipython notebook

【问题讨论】:

标签: python matplotlib pandas


【解决方案1】:

使用set_xlim+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())

编辑,每年都有xticklabel,而不是pandas中的默认每两年:

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

【讨论】:

  • 这可能是margins 有用的另一种情况。
  • 感谢您的建议。事实上,使用真正的日期对象而不是像我那样使用“字符串”可能是一个更好的主意。因为使用我的索引,您的解决方案不起作用。当然,你的解决方案是更好的。我会先玩边距
  • @ChristianRapp 不,让你的索引Date 对象可能是一个更好的解决方案
  • 如果我使用日期作为索引,如何设置在 x 轴上显示哪些刻度?现在该图仅每隔一年显示一次标签,但我希望显示每一年。
  • @ChristianRapp, pandas 自动做了很多事情,在这里它确定每年都有标签太忙了,每两年标签一次。请参阅编辑以获取解决方法。这确实意味着更多的工作,但在pandas 中使用Dateindex 处理time series 数据通常是一个好主意。
【解决方案2】:
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-ticks,请查看:

# 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)

这意味着如果您平移刻度标签将保持不变,但会在随机位置。这与更改 xlim 的问题相同,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 上创建了一个问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 2020-12-05
    • 2017-03-04
    • 1970-01-01
    • 2022-09-27
    • 2017-09-28
    • 2013-03-29
    相关资源
    最近更新 更多