Why is the first of the month automatically plotted as tick in matplotlib.plot_date?

萝らか妹 提交于 2021-02-11 09:40:49

问题


I have a geodataframe with date as string and Date as a datetime64[ns]. I am using matplotlib 3.0.2. I've tried clearing the data using plt.cla(), plt.clear() and plt.clf() as mentioned in other posts and questions but no matter what, the data plots what seems to be a major and minor axis formatting without any prompting - assuming that in plot_date the first of the month is the "major" axis. This is my graph (edited for clarity). It seems caused by new updates in 3.0.2 (from 2.1.0) it's hard to figure out what exactly is causing this

I saw this question/answer which seems to be in the vein of my issue, but in this instance it was desired to be using sub dates, etc, while I am confused since this has not been a consistent issue for me in other similar datasets.

Dataframe:
          Date    var_name
106 2018-04-03  0.79132056
216 2018-04-09  0.75112718
546 2018-06-12  0.73359674
646 2018-07-03  0.72600174
706 2018-07-23  0.71263647



figsize=(14,10)
fig, ax = plt.subplots(figsize=figsize)
data['Date'] = pd.to_datetime(data['Date'])

plt.xticks(rotation=30, ha='right')
plt.grid(color='k', lw=0.2)

plt.plot_date(data.Date, data.var_name)

UPDATE

Thanks to Jody and ImportanceOfBeingErnest for pointing out this was caused by a change in kwargs in matplotlib version 3.0.2 that is fixed in 3.1 where interval_multiples=True is now the default to plot the first of the month in addition to other ticks. @ImportanceOfBeingErnest was a reviewer.

PR link

most relevant matplotlib issue #12925. Matplot lib issue #9978 is also relevant


回答1:


Thank you to @TheImportanceOfBeingErnest and @JodyKlymak for their comments to suggest using the AutoDateLocator and MonthLocator. The following snippet ended up being my workaround. Final figure

Approach with more control:

figsize=(14,10)
fig, ax = plt.subplots(figsize=figsize)
data['Date'] = pd.to_datetime(data['Date'])

plt.xticks(rotation=30, ha='right')
plt.grid(color='k', lw=0.2)

months = matplotlib.dates.MonthLocator()
ax.xaxis.set_major_locator(months)
year_month = matplotlib.dates.DateFormatter('%Y-%m')
ax.xaxis.set_major_formatter(year_month)

plt.plot_date(data.Date, data.var_name)

Approach still using AutoDateLocator while retaining old behavior:

locator = matplotlib.dates.AutoDateLocator(interval_multiples=False)
ax.xaxis.set_major_locator(locator)


来源:https://stackoverflow.com/questions/54031757/why-is-the-first-of-the-month-automatically-plotted-as-tick-in-matplotlib-plot-d

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