2016-09-27 503 views
8

我正在绘制使用pandas .p​​lot()的时间序列,并且想要查看每个月显示为x-tick。pandas .p​​lot()x轴刻度频率 - 如何显示更多刻度?

这里是集结构 data set

这里是.plot()

enter image description here

我试图用实例从其他岗位和matplotlib documentation和做类似的结果

ax.xaxis.set_major_locator(
    dates.MonthLocator(revenue_pivot.index, bymonthday=1,interval=1)) 

但是,删除所有的蜱:(

我也试过通过xticks = df.index,但它没有改变任何东西。

在x轴上显示更多刻度的方法是什么?

+1

你是否将日期解析为日期时间? –

+0

@DemetriP谢谢。看起来至少是问题的一部分。现在使用ax.xaxis.set_major_locator之后,我确实看到了蜱虫......唯一的问题是现在我每年只看到一个蜱虫。 我明显使用MonthLocator错误。 – Rotkiv

回答

2

做的正确的方式描述here 使用x_compat参数,它可以抑制自动剔分辨率调节

df.A.plot(x_compat=True)

+0

不适合我。 Python 3.6,熊猫0.19.2。任何想法为什么? – famargar

+0

我都不是,python 3.6和pandas 0.22 – seanysull

+1

@seanysull修复确切的信息应该很简单。不幸的是,这个问题没有[MCVE](https://stackoverflow.com/help/mcve),因此很难判断你的数据帧等是否与OPs一样(因为OP自己回答说他们可能已经做了一些“后面的事情”那些解决问题的场景“)。我个人会问另一个问题,连接到这个解释为什么这不适合你。 – DavidG

2

无需通过任何参数传递给MonthLocator。请确保使用x_compat拨打df.plot()每个@ Rotkiv的回答。

import pandas as pd 
import numpy as np 
import matplotlib.pylab as plt 
import matplotlib.dates as mdates 

df = pd.DataFrame(np.random.rand(100,2), index=pd.date_range('1-1-2018', periods=100)) 
ax = df.plot(x_compat=True) 
ax.xaxis.set_major_locator(mdates.MonthLocator()) 
plt.show() 
1

你也可以格式化DateTimeIndex“手动”使用大熊猫Timestamp对象的属性的熊猫的x轴蜱和标签。

我发现,不是使用matplotlib.dates定位器,其工作的其他日期时间格式比熊猫(如果我没有记错的话),因此有时会表现出奇怪的行为,如果日期没有相应转换容易得多。

这里是一个通用的例子,显示了基于Timestamp对象大熊猫的属性每个月的第一天,作为一个标签:

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 


# data 
dim = 8760 
idx = pd.date_range('1/1/2000 00:00:00', freq='h', periods=dim) 
df = pd.DataFrame(np.random.randn(dim, 2), index=idx) 

# select tick positions based on timestamp attribute logic. see: 
# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Timestamp.html 
positions = [p for p in df.index 
      if p.hour == 0 
      and p.is_month_start 
      and p.month in range(1, 13, 1)] 
# for date formatting, see: 
# https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior 
labels = [l.strftime('%m-%d') for l in positions] 

# plot with adjusted labels 
ax = df.plot(kind='line', grid=True) 
ax.set_xlabel('Time (h)') 
ax.set_ylabel('Foo (Bar)') 
ax.set_xticks(positions) 
ax.set_xticklabels(labels) 

plt.show() 

产量:

enter image description here

希望这有助于!