Lesson 4. Customize Matplotlibe Dates Ticks on the x-axis in Python


In this tutorial, you will explore more advanced plotting techniques using matplotlib.

Learning Objectives

At the end of this activity, you will be able to:

  • Customize date formats on a matplotlib plot in python`

What You Need

You need Python 3.x and Jupyter notebooks to complete this tutorial. Also you should have an earth-analytics directory setup on your computer with a /data directory with it.

Download Colorado Flood Teaching Data Subset data

In this lesson you will learn how to format the time and date stamps drawn on a matplotlib plot axis.

# import required python packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import os
plt.ion()
import earthpy as et

# matplotlibdate format modules
from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates

os.chdir(os.path.join(et.io.HOME, 'earth-analytics'))

# set parameters so all plots are consistent
plt.rcParams['figure.figsize'] = (8, 8)

# prettier plotting with seaborn
import seaborn as sns; 
sns.set(font_scale=1.5)
sns.set_style("whitegrid")

In the previous lessons you downloaded and imported data from figshare into Python using the following code.

# to begin, read in the data
boulder_daily_precip = pd.read_csv('data/colorado-flood/precipitation/805325-precip-dailysum-2003-2013.csv', 
                                   parse_dates=['DATE'], 
                                   na_values=['999.99'],
                                   index_col = ['DATE'])

# subset the data as we did previously
precip_boulder_AugOct = boulder_daily_precip["2013-08-15" :"2013-10-15"]


# view first few rows of data
precip_boulder_AugOct.head()
DAILY_PRECIPSTATIONSTATION_NAMEELEVATIONLATITUDELONGITUDEYEARJULIAN
DATE
2013-08-210.1COOP:050843BOULDER 2 CO US1650.540.0338-105.28112013233
2013-08-260.1COOP:050843BOULDER 2 CO US1650.540.0338-105.28112013238
2013-08-270.1COOP:050843BOULDER 2 CO US1650.540.0338-105.28112013239
2013-09-010.0COOP:050843BOULDER 2 CO US1650.540.0338-105.28112013244
2013-09-090.1COOP:050843BOULDER 2 CO US1650.540.0338-105.28112013252

Plot the data.

# plot the data
fig, ax = plt.subplots(figsize = (10,8))
ax.scatter(precip_boulder_AugOct.index.values, 
       precip_boulder_AugOct['DAILY_PRECIP'].values,
       color='purple')
ax.set(xlabel="Date", ylabel="Precipitation (Inches)")
ax.set(title="Daily Precipitation (inches)\nBoulder, Colorado 2013");
Scatterplot showing daily precipitation in Boulder, Colorado.
Scatterplot showing daily precipitation in Boulder, Colorado.

Reformat Dates in Matplotlib

You can change the format of a date on a plot axis too in matplotlib using the DateFormatter module.

To begin you need to import DateFormatter from matplotlib. Then you specify the format that you want to use for the date DateFormatter using the syntax: ("%m/%d") where each %m element represents a part of the date as follows:

%Y - 4 digit year %y - 2 digit year %m - month %d - day

To implement the custom date, you then: define the date format: myFmt = DateFormatter("%m/%d")

This a date format that is month/day so it will look like this: 10/05 which represents October 5th. Here you can customize the date to look like whatever format you want.

Then you call the format that you defined using the set_major_formatter() method. ax.xaxis.set_major_formatter(myFmt)

This applies the date format that you defined above to the plot.

# Define the date format
myFmt = DateFormatter("%m/%d") 

# plot the data
fig, ax = plt.subplots()
ax.scatter(precip_boulder_AugOct.index.values, 
       precip_boulder_AugOct['DAILY_PRECIP'].values,
       color='purple')
ax.set(xlabel="Date", ylabel="Precipitation (Inches)")
ax.set(title="Daily Precipitation (inches)\nBoulder, Colorado 2013")

# tell matplotlib to use the format specified above
ax.xaxis.set_major_formatter(myFmt); 
Scatterplot showing daily precipitation with the x-axis dates cleaned up so they are easier to read.
Scatterplot showing daily precipitation with the x-axis dates cleaned up so they are easier to read.

X-Lable Ticks and Dates

Time specific ticks can be added along the x-axis. For example, large ticks can indicate each new week day and small ticks can indicate each day.

The function xaxis.set_major_location() controls large ticks, and the function xaxis.set_minor_locator controls the smaller ticks.

# define the date format
myFmt = DateFormatter("%m-%d") 

# plot
fig, ax = plt.subplots()
ax.scatter(precip_boulder_AugOct.index.values, 
       precip_boulder_AugOct['DAILY_PRECIP'].values,
       color='purple')
ax.set(xlabel="Date", ylabel="Precipitation (Inches)",)
ax.set_title("Daily Precipitation (inches)\nBoulder, Colorado 2013")
     
#ax.xaxis.set_major_locator(mdates.WeekdayLocator())
ax.xaxis.set_major_formatter(myFmt) 

Scatterplot showing daily precipitation with the x-axis dates cleaned up and the format customized so they are easier to read.
Scatterplot showing daily precipitation with the x-axis dates cleaned up and the format customized so they are easier to read.

You can add minor ticks to your plot too. Given we are using seaborn to customize the look of our plot, minor ticks are not rendered. But if you wanted to add day ticks to a plot that did have minor ticks turned “on” you would use:

ax.xaxis.set_minor_locator(mdates.DayLocator())

mdates.DayLocator() adds a tick for each day.

Additional Resources

Here are some additional matplotlib

Leave a Comment