【问题标题】:Increasing Frequency of x-axis labels for dates on DataFrame plotDataFrame图上日期的x轴标签频率增加
【发布时间】:2016-06-01 17:15:02
【问题描述】:

我有一个包含两列的 pandas DataFrame:month_of_sale 是日期,number_of_gizmos_sold 是数字。

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

这是我桌子的df.head()

这就是它的情节: df.plot(y='number_of_gizmos_sold', figsize=(15,5))

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

我尝试过的

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

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

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

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

  • 0002 作为年份是怎么回事?
  • 为什么我还有旧的Jul 标签?

【问题讨论】:

  • 试一试plt.xticks(np.arange(0,len(df),5))
  • @bernie,改变 x 轴范围但不调整刻度或标签的频率
  • 嗯,好的。我认为它在熊猫中的工作方式不同。我的错。

标签: pandas matplotlib plot axis-labels


【解决方案1】:

我没有将问题追溯到其根源,但如果您致电 ax.plot,请按照 bmu's solution 而不是df.plot,那么您可以使用配置结果 ax.xaxis.set_major_locatorax.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()

【讨论】:

  • 你说得对,不知怎的,Pandas 忽略了(或滥用)这些参数。如果我使用fig, ax = plt.subplots(); ax.plot(df.index, df['gizmos']),那么它可以工作!
猜你喜欢
  • 2014-09-24
  • 2020-10-01
  • 2016-12-14
  • 1970-01-01
  • 2017-03-14
  • 1970-01-01
  • 2017-10-28
相关资源
最近更新 更多