为pandas/matplotlib设置xlim,其中index为字符串 [英] Set xlim for pandas/matplotlib where index is string

查看:52
本文介绍了为pandas/matplotlib设置xlim,其中index为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用字符串作为索引的熊猫数据框.当我的数据帧索引是对象类型时,如何为 x 轴设置 xlim?我尝试将另外两个年份分别添加到末尾,并在开始时添加所有数据集均为np.nan的第一年,但这没有用.

I have a pandas dataframe that uses strings as index. How can I set xlim for the x axis when my dataframe index is of type object? I tried adding two additional years one at the end and one at the beginning where all datasets are np.nan but that didn't work.

这是数据框

索引的数据类型是对象

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

这是情节

所以我想在 x 轴上留出一些额外的空间,以便更好地显示拳头和去年的值.我能做什么?

So I would like to have some extra space on the x-axis in so the values for the fist and last year are better visible. What could I do?

编辑:

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

Here is a minimal example using objects and not date objects as index

ipython 笔记本

推荐答案

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,请查看:

which gets you the plot. To take a look at how the x-ticks are getting dealt with look at:

# 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 最初设置绘图的方式,刻度标签与数据完全分离.

This means that if you pan around the tick labels will stay the same, but will be at random positions. This is the same problem as changing the xlim, the way pandas sets up the plot initially the tick labels are completely decoupled from the data.

一种解决此问题的(详细)方法是:

One (verbose) way to fix this is:

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

无论您将索引设置为什么(字符串与日期),这都会起作用

This will work no matter what you set your index to (strings vs dates)

我创建了一个熊猫问题 https://github.com/pydata/pandas/issues/7612

I have created an issue with pandas https://github.com/pydata/pandas/issues/7612

这篇关于为pandas/matplotlib设置xlim,其中index为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆