Pandas: how to plot timeseries based charts?

In this quick recipe we’ll learn how to quickly create a chart that displays time series key performance indicator data.

Let’s quickly start by creating some random data for this exercise:

import pandas as pd
import numpy as np # used for generating random data
np.random.seed(10)

date_range =  pd.date_range('2020-01-01','2020-11-01', freq ='MS')

raw_data = {'time': date_range, \
                     'sales': [x for x in np.random.randint(30, 100, \
                               len(date_range) )]}

# create dataframe from dictionary

sales = pd.DataFrame.from_dict(raw_data)

sales.head()

Here’s our dataframe header:

timesales
02020-01-0179
12020-02-0191
22020-03-0187
32020-04-0174
42020-05-0166

Using DataFrame.plot() to draw datetime charts in Pandas

Now that we have some data available, let’s take a look at how to quickly draw our plot using the DataFrame.plot() method that is readily made available in Pandas.

sales.plot(x= 'time', y= 'sales', kind='line');

This will render a simple line plot. Pandas took care of converting the datetime values of the ‘time’ column to months automatically.

And a bit more elaborated version:

sales.plot(x= 'time', 
           y= 'sales', 
           kind='line',
           figsize = (10,6), 
           title="Sales Over Time",
           grid=True , 
           style = 'r');

Leave a Comment