88

I am looking to edit the formatting of the dates on the x-axis. The picture below shows how they appear on my bar graph by default. I would like to remove the repetition of 'Dec' and '2012' and just have the actual date numbers along the x-axis.

Any suggestions as to how I can do this?

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Osmond Bishop
  • 7,560
  • 14
  • 42
  • 51
  • 1
    The answer here worked for me: http://stackoverflow.com/questions/30133280/pandas-bar-plot-changes-date-format – Mahdi Sep 21 '16 at 08:53

4 Answers4

147

In short:

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

Many examples on the matplotlib website. The one I most commonly use is here

Paul H
  • 65,268
  • 20
  • 159
  • 136
56

While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.

So for everyone in need here is a full working example:

from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)

myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)

## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
Robino
  • 4,530
  • 3
  • 37
  • 40
5

From the package matplotlib.dates as shown in this example the date format can be applied to the axis label and ticks for plot.

Below I have given an example for labeling axis ticks for multiplots

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

df = pd.read_csv('US_temp.csv')
plt.plot(df['Date'],df_f['MINT'],label='Min Temp.')
plt.plot(df['Date'],df_f['MAXT'],label='Max Temp.')
plt.legend()
####### Use the below functions #######
dtFmt = mdates.DateFormatter('%b') # define the formatting
plt.gca().xaxis.set_major_formatter(dtFmt) # apply the format to the desired axis
plt.show()

As simple as that

Amirtha Rajan
  • 605
  • 10
  • 19
2

This wokrs prfectly for me

import matplotlib.pyplot as plt
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
                               AutoMinorLocator)
import matplotlib.dates as mdates

dtFmt = mdates.DateFormatter('%Y-%b') # define the formatting
plt.gca().xaxis.set_major_formatter(dtFmt) 
# show every 12th tick on x axes
plt.gca().xaxis.set_major_locator(mdates.MonthLocator(interval=1))
plt.xticks(rotation=90, fontweight='light',  fontsize='x-small',)

formating example

RiveN
  • 2,595
  • 11
  • 13
  • 26
lepi
  • 31
  • 3