I am following this demo to use matplotlib.dates
in order to add "ticks" per month using pandas series data. My pandas series is named weekly_data1991
Datetime
1991-01-08 2245
1991-01-09 2678
1991-01-10 2987
1991-01-11 2258
....
Freq: W-SUN, dtype: int64
Unfortunately, this wipes out many of the "default" labels when just using straightforward matplotlib.pyplot.plot()
For example, if I use
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12,5))
plt.plot(weekly_data1991, color = 'green' )
Using matplotlib.dates
,
from matplotlib import dates as mdates
fig = plt.figure(figsize=(12,5))
ax = plt.subplot(111)
plt.plot(weekly_data1991, color = 'green' )
years = mdates.YearLocator()
months = mdates.MonthLocator()
yearsFmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
ax.grid(which='both', axis='x')
plt.show()
which outputs the plot
I can I put the labels back in?
I find (Matplotlib 1.4.3) that I can get both major and minor tick labels formatted as dates using mdates.DateFormatter
as follows.
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
df = pd.read_csv('data.csv', sep=None, names=('Datetime', 'values'),
parse_dates=['Datetime'])
fig = plt.figure(figsize=(12,5))
ax = plt.subplot(111)
plt.plot(df['Datetime'], df['values'], color = 'green' )
years = mdates.YearLocator()
months = mdates.MonthLocator()
yearsFmt = mdates.DateFormatter('%Y')
monthsFmt = mdates.DateFormatter('%b')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_formatter(monthsFmt)
ax.xaxis.set_minor_locator(months)
ax.grid(which='both', axis='x')
for tick in ax.get_xaxis().get_major_ticks():
tick.set_pad(15)
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.