+-

我有一个使用字符串作为索引的pandas数据帧.当我的数据帧索引是object类型时,如何为x轴设置xlim?我尝试在结尾添加另外两年,在开始时添加一个,其中所有数据集都是np.nan但是没有用.
这是数据帧
索引的数据类型是object
df.index
Out[52]: Index(['2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012'], dtype='object')
这是情节
所以我希望在x轴上有一些额外的空间,这样第一年和去年的值就更明显了.我能做什么?
编辑:
这是使用对象而不是日期对象作为索引的最小示例
ipython notebook
最佳答案
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创建了一个问题
点击查看更多相关文章
转载注明原文:python – 为pandas / matplotlib设置xlim,其中index是string - 乐贴网