Matplotlib plot_date – Complete tutorial

In this Python tutorial, we will discuss How to plot the data consist of dates in matplotlib in python, and we will also cover the following topics:

  • Matplotlib plot_date
  • Matplotlib plot_date line
  • Matplotlib plot_date scatter
  • Matplotlib plot_date multiple line
  • Matplotlib plot_date linestyle
  • Matplotlib plot_date color
  • Matplotlib plot_date date format
  • Matplotlib plot_date date conversion
  • Matplotlib plot_date date on x-axis
  • Matplotlib plot_date vertical line at specified date
  • Matplotlib plot_date xticks

Matplotlib plot_date

In the pyplot module of the matplotlib library plot_date() is a function. plot_date() method is basically used to plot data that consists of dates.

The syntax is given as below:

matplotlib.pyplot.plot_date(x ,y, fmt='o', tz=None, xdate=True, ydate=False, data=None, **kwargs)

In the above syntax, the following parameters are used which are outlined below:

  • x: The horizontal coordinate of the data points. An array-like structure is used to represent this coordinate. If xdate is True the value of x coordinate is converted as matplotlib dates.
  • y: The vertical coordinate of the data points. An array-like structure is used to represent this coordinate. If ydate is True the value of x coordinate is converted as matplotlib dates.
  • fmt: fmt is an optimal parameter. It has a string structure i.e. contains the string value. Basically, it is used to define color, linestyle, markersize, etc.
  • tz: tz stands for Time Zone. It contains a timezone string. Basically, it is used to labeling the dates. By default: ‘UTC’.
  • xdate: xdate contains boolean values and it is an optional parameter. If xdate is True, the x-axis will be depicted as Matplotlib dates. By default: True.
  • ydate: ydate contains a boolean value and it is also an optional parameter. If ydate is True, the y-axis will be depicted as Matplotlib dates. By default: True.
  • kwargs: kwargs stands for Keyword arguments. It basically, control the properties of the return line. For example, animated, clip_bx, color, etc are examples of property.

Return: plot_date() method returns a 2D line.

Let’s do an example for understanding the concept:

# Import Libraries

import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import drange
import numpy as np
   
d1 = datetime.datetime(2021, 7, 2)
d2 = datetime.datetime(2021, 7, 12)
delta = datetime.timedelta(hours = 48)
dates = drange(d1, d2, delta)
   
y = np.arange(len(dates))
   
plt.plot_date(dates, y**3)

plt.tick_params(axis='x', which='major', labelsize=6)

plt.tight_layout()
plt.show()
Matplotlib plot_date
plot_date()

In the above example, firstly we import important libraries such as datetime for date and time modules, matplotlib for generating graphs, drange for adjusting the range between the initial and final dates, and NumPy for the array.

We use datetime.datetime() module to set date and datetime.timedelta() to set hours and lastly, we use drange() module to set the equal distance dates.

plot_date() function to plot graph contains dates , tick_params() to set the space between x-axis, tight_layout() module to adjust the plot. And finally. we use the last method show() to display the plotted graph.

Read How to install matplotlib python

Matplotlib plot_date line

We will create a line plot of dates by using the matplotlib library pyplot module which has plot_date() function.

The syntax for this is as below:

matplotlib.pyplot.plot_date(x, y, linestyle='None')

Let’s understand the concept of creating a date lined graph with the help of the below example:

# Import Libraries

import matplotlib.pyplot as plt
from datetime import datetime, timedelta


dates = [
    datetime(2021, 10, 21),
    datetime(2021, 10, 22),
    datetime(2021, 7, 24),
    datetime(2021, 10, 25),
    datetime(2021, 10, 26),
]

y = [2, 4, 4.5, 6, 5]

plt.plot_date(dates, y, linestyle = 'dotted')
plt.tight_layout()
plt.show()
Matplotlib plot_date line
plot_date()

In the above example, we will use the dotted style to create a line graph for plotting dates.

Then we use datetime() module for entering the date. Finally, we pass the dates and values of y to plot_date().

In the last step, we call a show() method to display plotted date-lined graph.

Read Matplotlib plot a line

Matplotlib plot_date scatter

We will create a scatter plot of dates by using the matplotlib library pyplot module which has plot_date() function.

The syntax for this is as below:

matplotlib.pyplot.plot_date(x, y)

Note: If you do not mention linestyle, by default it always gives a scatter plot.

Let’s understand the concept of creating a date scatter graph with the help of the below example:

# Import Libraries

import matplotlib.pyplot as plt
from datetime import datetime, timedelta
plt.style.use('dark_background')

dates = [
    datetime(2021, 10, 21),
    datetime(2021, 7, 24),
    datetime(2021, 8, 25),
    datetime(2021, 10, 26),
]

y = [2, 4, 4.5, 6]

plt.plot_date(dates, y)
plt.tight_layout()
plt.show()
Matplotlib plot_date scatter
plot_date()

In the above example, we will plot a scatter plot for plotting dates.

Then we use datetime() module for entering the date. Finally, we pass the dates and values of y to plot_date().

In the last step, we call a show() method to display plotted date-lined graph.

Read Python plot multiple lines using Matplotlib

Matplotlib plot_date multiple line

We will create multiple lines within the same plot to plot dates by using the matplotlib library pyplot module which has plot_date() function.

READ:  How to Install TensorFlow? [Windows, Linux and MacOS]

The syntax for this is as below:

matplotlib.pyplot.plot_date(x, y)

Let’s understand the concept of creating a date scatter graph with the help of the below example:

# Import Libraries
import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import drange
import numpy as np

plt.style.use('seaborn')
   
d1 = datetime.datetime(2021, 7, 2)
d2 = datetime.datetime(2021, 7, 12)
delta = datetime.timedelta(hours = 48)
dates = drange(d1, d2, delta)
   
y = np.arange(len(dates))
   
plt.plot_date(dates, y**3, linestyle='dashed')
plt.plot_date(dates, y**5, linestyle='dashed')

plt.tight_layout()
plt.show()
Matplotlib plot_date multiple line
plot_date()

In the above example, we use datetime.datetime() module to set date and datetime.timedelta() to set hours and lastly, we use drange() module to set the equal distance dates.

Finally, we pass the dates and values of y to plot_date() and show() method to display plotted date-lined graph.

Read What is matplotlib inline

Matplotlib plot_date linestyle

plot_date() method is basically used to plot data that consists of dates and linestyle specify all the variety of lines you can use to plot.

The Followings are the linestyle:

  • solid
  • dashdot
  • dotted
  • dashed

Let’s discuss some common types of line styles:

plot_date linestyle – solid

Let’s have a look at an example and try to understand the concept:

# Import Libraries

import matplotlib.pyplot as plt
from datetime import datetime, timedelta

dates = [ 
          datetime(2021, 8, 21),
          datetime(2022, 8, 22),
          datetime(2023, 8, 23), 
        ]

y = [0, 1, 2]

plt.plot_date(dates, y, linestyle='solid')

plt.tick_params(axis='x', which='major', labelsize=8)
plt.tight_layout()
plt.show()
Matplotlib plot_date linestyle
plot_date()

In this above example, in plot_date() method we add a parameter linestyle and set their value to solid or ‘-‘.

Read Matplotlib plot bar chart

plot_date linestyle – dashdot

Let’s have a look at an example and try to understand the concept:

# Import Libraries

import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import drange
import numpy as np

plt.style.use('seaborn')
   
d1 = datetime.datetime(2021, 7, 2)
d2 = datetime.datetime(2021, 7, 12)
delta = datetime.timedelta(hours = 48)
dates = drange(d1, d2, delta)
   
y = np.arange(len(dates))
   
plt.plot_date(dates, y**3, linestyle='dashdot')

plt.tight_layout()
plt.show()
plot_date linestyle dashdot
plot_date()

In this above example, in plot_date() method we add a parameter linestyle and set their value to dashdot or ‘-.’.

plot_date linestyle – dotted

Let’s have a look at an example and try to understand the concept:

# Import Libraries
import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import drange
import numpy as np

plt.style.use('seaborn')
   
d1 = datetime.datetime(2021, 7, 2)
d2 = datetime.datetime(2021, 7, 12)
delta = datetime.timedelta(hours = 48)
dates = drange(d1, d2, delta)
   
y = np.arange(len(dates))
   
plt.plot_date(dates, y**3, linestyle=':')

plt.tight_layout()
plt.show()
plot_date linestyle dotted
plot_date()

In this above example, in plot_date() method we add a parameter linestyle and set their value to dotted or ‘:’.

plot_date linestyle – dashed

Let’s have a look at an example and try to understand the concept:

# Import Libraries

# Import Libraries

import matplotlib.pyplot as plt
from datetime import datetime, timedelta
plt.style.use('dark_background')

dates = [
    datetime(2021, 10, 21),
    datetime(2021, 7, 24),
    datetime(2021, 8, 25),
    datetime(2021, 10, 26),
]

y = [2, 4, 4.5, 6]

plt.plot_date(dates, y, linestyle= 'dashed')
plt.tight_layout()
plt.show()
plot_date linestyle dashed
plot_date()

In this above example, in plot_date() method we add a parameter linestyle and set their value to dashed or ‘–‘ .

Read Matplotlib subplot tutorial

Matplotlib plot_date color

plot_date() method is basically used to plot data that consists of dates and the parameter color specify the different colors which we use to highlight different date plot lines.

The syntax for this is given below:

matplotlib.pyplot.plot_date(x, y, color=None)

Different colors available in matplotlib by using which you can easily differentiate between lines are given below:

  • Blue color: Write it as ‘blue’ or ‘b’.
  • Red color: Write it as ‘red’ or ‘r’.
  • Green color: Write it as ‘green’ or ‘g’ .
  • Cyan color: Write it as ‘cyan’ or ‘c’ .
  • Magenta color: Write it as ‘magenta’ or ‘m’ .
  • Yellow color: Write it as ‘yellow’ or ‘y’ .
  • Black color: Write it as ‘black’ or ‘k’ .
  • White color: Write it as ‘white’ or ‘w’ .

Let’s understand the concept of changing the color of plot lines with help of the below example:

# Import Libraries

import matplotlib.pyplot as plt
from datetime import datetime, timedelta
plt.style.use('dark_background')

dates = [
    datetime(2021, 10, 21),
    datetime(2021, 7, 24),
    datetime(2021, 8, 25),
    datetime(2021, 10, 26),
]

y = [0, 1, 2, 3]
y1= [2.5, 3.6, 2.8, 6.4]
y2= [3.6, 5.5, 9.7, 9.6]

plt.plot_date(dates, y, linestyle='dotted', color='red')
plt.plot_date(dates, y1, linestyle='solid', color='green')
plt.plot_date(dates, y2, linestyle='dashed', color='blue')

plt.tick_params(axis='x', which='major', labelsize=8)
plt.tight_layout()
plt.show()
Matplotlib plot_date color
plot_date()

In the above example, we use the plot_date() method for plotting data consist of date. To easily differentiate between the plotted lines we use the parameter color.

Here we plot three different data lines to plot dates and we use three different colors as red, green, blue to represent them.

Read Matplotlib best fit line

Matplotlib plot_date date format

plot_date() method is used for plotting the dates. By sometimes a programmer want’s to customize the look of tick marks or we say labels. So, matplotlib provides the functionality to change the format of the dates.

Date Format library

For formatting the dates in plot_date() you have to import library dates from matplotlib.

Syntax to import the library:

from matplotlib import dates as mpl_dates

DateFormatter module

Matplotlib provides a DateFormatter module by using which you can customize the format of the date as per your choice.

The syntax for this is given below:

DateFormatter('%x %x')

In the above syntax each %x, represents the parts of the date like month, date, year.

READ:  Python Turtle Graphics

Parts of the date or what %x represents:

  • %Y: Upper case Y represents the year in 4 digits.
  • %y: Lower case y represents the year in 2 digits.
  • %m: Lower case m represents the month as a number.
  • %b: Lower case b represents the month as a name.
  • %d: Lower case d represents the day as a digit.

How to separate day, month, and year in the date:

Generally, we use a separator to separate the parts of the date to overcome confusion. So, we can also add a character as a separator between the date.

Mostly we use two types of separators as given below:

  • Hyphen : –
  • Slash : \

The syntax to use the separator is given below:

DateFormatter('%x-%x')

Let’s understand the concept with the help of an example:

# Import Libraries

import pandas as pd
from datetime import datetime, timedelta
from matplotlib import pyplot as plt
from matplotlib import dates as mpl_dates

dates = [
          datetime(2021, 10, 21),
          datetime(2021, 7, 24),
          datetime(2021, 8, 25),
          datetime(2021, 10, 26),
]

y = [ 0, 1, 2, 3]

plt.plot_date(dates, y,)

date_format = mpl_dates.DateFormatter('%m/%d/%Y')
plt.gca().xaxis.set_major_formatter(date_format)

plt.tick_params(axis='x', which='major', labelsize = 7)
plt.show()
Matplotlib plot_date date format
plot_date()

In the above example, we change the format of the date: month as a digit, day as a digit, and year as 4 digits and use a slash separator to separate each of them.

plt.gca() method is used to get current axes to reference.

xaxis.set_major_formatter() method is used to set major ticker format.

Then we final pass date_format to plt.gca().xasix.set_major_formatter() method to do the customized formatting of the date.

Let’s take one more example to understand this more clearly:

# Import Libraries

import pandas as pd
from datetime import datetime, timedelta
from matplotlib import pyplot as plt
from matplotlib import dates as mpl_dates

dates = [
          datetime(2021, 10, 21),
          datetime(2021, 7, 24),
          datetime(2021, 8, 25),
          datetime(2021, 10, 26),
]

y = [ 0, 1, 2, 3]

plt.plot_date(dates, y,)

date_format = mpl_dates.DateFormatter('%b - %d - %y')
plt.gca().xaxis.set_major_formatter(date_format)

plt.tick_params(axis='x', which='major', labelsize = 6)
plt.show()
DateFormatter module
plot_date()

In the above example, we change the format of the date: month as a name, day as a digit, and year as 2 digits and use a hyphen separator to separate each of them.

plt.gca() method is used to get current axes to reference.

xaxis.set_major_formatter() method is used to set major ticker format.

Then we final pass date_format to plt.gca().xasix.set_major_formatter() method to do the customized formatting of the date.

Read Python string to list

Matplotlib plot_date() date conversion

The need for date conversion comes into existence because Matplotlib represents dates as float values.

In Python generally, dates are represented as datetime objects. So we need to convert the data into dates as datetime objects

The syntax for creating the datetime object is as given below:

import datetime
date = datetime.datetime(year, month, date, hour, minute, seconds, microseconds)

In the above syntax firstly we import the library datetime, then we use the method datetime.datetime() and pass the parameters.

Now you have a datetime object, so it is time to convert the object into floating-point numbers in the format of 0001-01-01- 00:00:00 UTC.

Functions for conversion:

Listed below functions are used for conversion and we have these functions in matplotlib.date() module.

  • date2num(): date2num() function converts datetime objects into float values representing days. The format used by this method is as hours, minutes, and seconds.
  • num2date(): num2date() function converts the float value representing days into datetime objects.
  • drange(dstart,dend,delta): drange() function returns the date range of float values in date format. Where start represents starting date, send represents the end date and delt represents the gap between or time interval between start and end date.

Let’s understand this concept with the help of an example:

# Import Libraries

import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import drange
import numpy as np
   
d1 = datetime.datetime(2021, 7, 2)
d2 = datetime.datetime(2021, 7, 12)
delta = datetime.timedelta(hours = 48)
dates = drange(d1, d2, delta)
   
y = np.arange(len(dates))
   
plt.plot_date(dates, y**3)

plt.tick_params(axis='x', which='major', labelsize=6)

plt.tight_layout()
plt.show()
Matplotlib plot_date() date conversion
plot_date()

In the above example, we create objects with the datetime.datetime() method and then we use the drange() method to get the date range in date format with a time interval gap of 48 hours.

Read Matplotlib subplots_adjust

Matplotlib plot_date date on x-axis

In this section, we will discuss how to plot dates on the x-axis and how we format them so the plot looks clean.

let’s have a look at the below example:

# Import Libraries

import pandas as pd
from datetime import datetime, timedelta
from matplotlib import pyplot as plt
from matplotlib import dates as mpl_dates

dates = [
          datetime(2021, 10, 21),
          datetime(2021, 7, 24),
          datetime(2021, 8, 25),
          datetime(2021, 10, 26),
]

y = [ 0, 1, 2, 3]

plt.plot_date(dates, y, linestyle='solid')
plt.show()
Matplotlib plot_date date on x-axis
plot_date()

See in this above output the x-axis represent dates, but they look so untidy and also overlap on each other.

Now, see the solution to overcome this problem:

In matplotlib, we have a function autofmt_xdate() which is used for auto-formatting of dates on the x-axis. Basically, this method is used to rotate the dates and align them in right.

The syntax of the autofmt_xdate() method is as below:

autofmt_xdate(self, bottom=0.2, rotation=30, ha=right, which=None)

In the above syntax, the following parameters are used which are outlined below:

  • bottom: bottom adjusts the bottom of subplots.
  • rotation: rotation rotates the xtick labels.
  • ha: specifies the horizontal alignment of xtick labels.
  • which: specifies which tickabels to rotate.
READ:  PyTorch Model Summary - Detailed Tutorial

Let’s understand this concept with the help of an example:

# Import Libraries

import pandas as pd
from datetime import datetime, timedelta
from matplotlib import pyplot as plt
from matplotlib import dates as mpl_dates

dates = [
          datetime(2021, 10, 21),
          datetime(2021, 7, 24),
          datetime(2021, 8, 25),
          datetime(2021, 10, 26),
]

y = [ 0, 1, 2, 3]

plt.plot_date(dates, y, linestyle='solid')
plt.gcf().autofmt_xdate()
plt.show()
Matplotlib plot_date date  format on x-axis
autofmt_xdate()

In the above example, we plot dates on the x-axis and use the method that auto-format the dates.

plt.gcf() method stands for Get Current Figure and use to get a reference of the current figure.

autofmt_xdate() method is used for the alignment of the x-axis ticks.

Conclusion! autofmt_xdate() gives a clear view of the dated plot without overlapping problems and with clear visibility of dates.

Read Matplotlib log log plot

Matplotlib plot_date vertical line at specified date

Once in a life programmers have the need to plot some data which consists of dates. Plotting weather, no. of births or deaths in a specific period, the balance sheet of year or month, etc in all such cases we need to plot dates.

Mostly these kinds of data are stored in a pandas data frame in form of CSV files or in simple format may be.

Syntax to plot vertical line at specified date:

matplotlib.pyplot,axvline(x=0, ymin=0, ymax=1, **kwargs)

In the above syntax, the following parameters are used which are outlined below:

  • x: To place the vertical line in data coordinates.
  • ymin: a vertical line starting position on the y-axis. It takes values between 0 and 1. 0 stands for the bottom of the axis and 1 stands for the top of the axis.
  • ymax: a vertical line ending position on the y-axis. It takes values between 0 and 1. 0 stands for the bottom of the axis and 1 stands for the top of the axis.
  • kwargs: specify properties to change the style, color, the linewidth of line.

Let’s understand the concept with the help of an example:

# Import Libraries

import pandas as pd
from datetime import datetime, timedelta
from matplotlib import pyplot as plt
from matplotlib import dates as mpl_dates

dates = [
          datetime(2021, 10, 21),
          datetime(2021, 7, 24),
          datetime(2021, 8, 25),
          datetime(2021, 10, 26),
]

y = [ 0, 1, 2, 3]

plt.plot_date(dates, y, linestyle='solid')
plt.axvline(x='2019-09-21',color='m', linestyle="--")
plt.gcf().autofmt_xdate()
plt.show()
Matplotlib plot_date vertical line at specified date
plot_date()

In the above example, we use axvline() method to plot vertical lines at specific dates.

Matplotlib plot_date xticks

In this section, we will discuss xticks() functions. Firstly understand what does ticks means, ticks are nothing but the marker which are used to show the specific point on the coordinate axis.

So basically, we have two types of ticks major ticks and minor ticks.

Whenever we plot a graph plot takes the default tick location and ticks label, ticks location is where we want to place that ticks, and the label is the name given to that ticks.

By default, the minor ticks are in the off state, so we can’t see the minor ticks in the plot. But we can see the major ticks, it can take the default value for the location and label.

What is xticks() method:

xticks() method helps to change the ticks location and the ticks label of the x-axis.

The syntax for this is given as below:

matplotlib.pyplot.xticks(ticks=None,labels=None, **kwargs)

In the above syntax, the following parameters are used which are outlined below:

  • ticks: specifies the array like list of xtick locations.
  • labels: specifies the array like list of labels to place at the given tick location.
  • kwargs: specifies extra properties to control the appearance of the labels at the x-axis.

Return:

  • location: list of location
  • label: list of the text object

Let’s understand this concept with the help of an example:

# Import Libraries

import pandas as pd
from datetime import datetime, timedelta
from matplotlib import pyplot as plt
from matplotlib import dates as mpl_dates

dates = [
          datetime(2021, 10, 21),
          datetime(2021, 7, 24),
          datetime(2021, 8, 25),
          datetime(2021, 10, 26),
          datetime(2021, 10, 21),
          datetime(2021, 7, 24),
          datetime(2021, 8, 25),
          datetime(2021, 10, 26),
]

y = [ 0, 1, 2, 3, 5, 4, 3, 6]

plt.plot_date(dates, y, linestyle='solid')
plt.gcf().autofmt_xdate()
plt.xticks(x=['2021-08-15','2021-10-26'], color='r')
Matplotlib plot_date without xticks
plot_date() without xticks()

Above output is without xticks() method.

Matplotlib plot_date xticks
plot_date()

Above output is with xticks() method.

In this above example, we use the xticks() method to change the ticks location and the ticks label of the x-axis and also change its color to red.

Related Posts:

In this Python tutorial, we have discussed the “Matplotlib plot_date” and we have also covered some examples related to it. There are the following topics that we have discussed in this tutorial.

  • Matplotlib plot_date
  • Matplotlib plot_date line
  • Matplotlib plot_date scatter
  • Matplotlib plot_date multiple line
  • Matplotlib plot_date linestyle
  • Matplotlib plot_date color
  • Matplotlib plot_date date format
  • Matplotlib plot_date date conversion
  • Matplotlib plot_date date on x-axis
  • Matplotlib plot_date vertical line at specified date
  • Matplotlib plot_date xticks