Basic Timeseries chart with Mathplotlib

MP
2 min readMay 17, 2020

--

Last week I started to generate my own covid 19 tracker using python. I will write separately on the journey, here we will focus on problem that I faced to generate timeseries chart with Mathplotlib.

For the tracker I started to download data everyday with the simple scrapper I wrote by myself.

The data looks like this …

date,active_count,cure_count,death_count,migrated,source

12/05/20 07:35:04,46008,22454,2293,1,https://www.mohfw.gov.in/

13/05/20 08:56:46,47480,24385,2415,1,https://www.mohfw.gov.in/

14/05/20 14:10:50,49219,26234,2549,1,https://www.mohfw.gov.in/

As you can see its a timeseries data which seems simple to plot.

So I read in the data with pandas read_csv api as follows

self.dataf = pd.read_csv(“covid_india.csv”, parse_dates=True)

And plotted as follows self.dataf.plot()

This gives us following plot

Plain plot of dataframe

You will notice x axis does not show dates, which is desirable for clarity.

Plain plot does not help that means we need to break the dataframe to separate date series and remaining dataframe (data points).

Here is how new code looks like

import matplotlib.pyplot as plt
# self.dataf.iloc[:,1:-1] returns 1 to last col dataframe
# self.dataf['date'] returns date series
plt.plot(self.dataf['date'],self.dataf.iloc[:,1:-1])

But this will fail as ‘date’ column has date as first part while year last part and panda does not know about this.

So we provide panda this information

pd.to_datetime(self.dataf[‘date’], dayfirst=True)

so overall code looks like this

import matplotlib.pyplot as pltplt.plot(pd.to_datetime(self.dataf['date'], dayfirst=True).dt.date,self.dataf.iloc[:,1:-1])
plt.show()

The plot looks as follows —

We will look at advanced timeseries usecase when I show Daily Percentage Change code.

Did you have a better way let me know, i would like to know

--

--

MP
MP

Written by MP

Startup guy. Loves Programming

No responses yet