x轴标签在DataFrame图上显示日期的频率增加 [英] Increasing Frequency of x-axis labels for dates on DataFrame plot

查看:244
本文介绍了x轴标签在DataFrame图上显示日期的频率增加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两列的pandas DataFrame:month_of_sale是日期,而number_of_gizmos_sold是数字.

I have a pandas DataFrame with two columns: month_of_sale which is a date, and number_of_gizmos_sold which is a number.

我正在尝试增加x轴上标签的频率,以便于阅读,但我做不到!

I'm trying to increase the frequency of the labels on the x-axis so it's easier to read, but I can't!

这是我的桌子的df.head():

,它是这样绘制的: df.plot(y='number_of_gizmos_sold', figsize=(15,5))

and this is what it plots: df.plot(y='number_of_gizmos_sold', figsize=(15,5))

我想增加标签的频率,因为它们之间有很大的空间.

I'd like to increase the frequency of the labels, because there's a big space in between them.

plot.xaxis.set_major_locator(MonthLocator()),但这似乎进一步增加了标签之间的距离.

plot.xaxis.set_major_locator(MonthLocator()) but that seems to increase the distance between the labels even more.

plot.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))

奇怪的是,我最终得到了这个:

Strangely, I end up with this:

最后一个情节给我提出的问题是:

The questions that last plot raises for me are:

  • 那一年的0002是什么?
  • 那为什么我仍然还有旧的Jul标签?
  • What's up with 0002 as the year?
  • And why do I still have the old Jul labels there too?

推荐答案

我尚未将问题追溯到其根源,但根据 bmu的 解决方案,如果您致电ax.plot 而不是df.plot,则可以使用以下命令配置结果 ax.xaxis.set_major_locatorax.xaxis.set_major_formatter.

I haven't traced the problem back to its source, but per bmu's solution, if you call ax.plot instead of df.plot, then you can configure the result using ax.xaxis.set_major_locator and ax.xaxis.set_major_formatter.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
np.random.seed(2016)

dates = pd.date_range('2013-03-01', '2016-02-01', freq='M')
nums = (np.random.random(len(dates))-0.5).cumsum()
df = pd.DataFrame({'months': dates, 'gizmos': nums})
df['months'] = pd.to_datetime(df['months'])
df = df.set_index('months')

fig, ax = plt.subplots()
ax.plot(df.index, df['gizmos'])
# df.plot(y='gizmos', ax=ax)
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=2))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()
plt.show()

这篇关于x轴标签在DataFrame图上显示日期的频率增加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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