pandas - DataFrame图上日期的x轴标签频率增加

标签 pandas matplotlib plot axis-labels

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

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

这是我的表的 df.head():

DataFrame.head()

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

DataFrame.plot()

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

我尝试过的

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

enter image description here

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

奇怪的是,我最终得到了这个: enter image description here

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

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

最佳答案

我没有追查问题的根源,但根据 bmu's solution , 如果你调用 ax.plot 而不是 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()

enter image description here

关于pandas - DataFrame图上日期的x轴标签频率增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35517038/

相关文章:

python - 如何在 matplotlib 中绘制半无限线(射线)?

python - 为 pandas.io.json_normalize 提供默认值

python - 根据数据框中的位置计算元素

python - 将文本数据添加到未知的特定散点

r - 沿线性回归线绘制条件密度曲线 `P(Y|X)`

r - 如何使用基本 R 图为数据中不存在的日期添加轴刻度

r - 覆盖ggplot2中的多个stat_function调用

python - 重新格式化 Dataframe 列,以便将任何数字月份子字符串替换为月份字符串

python - 有没有办法将 Pandas 数据框打印为可复制代码?

python - 不同图形上 Y Axis 的比例相同