Increasing Frequency of x-axis labels for dates on DataFrame plot

北战南征 提交于 2020-01-12 06:00:10

问题


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

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

Here is the df.head() of my table:

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.

What I've tried

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:

  • What's up with 0002 as the year?
  • And why do I still have the old Jul labels there too?

回答1:


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



来源:https://stackoverflow.com/questions/35517038/increasing-frequency-of-x-axis-labels-for-dates-on-dataframe-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!