Categories
data science

Smooth Line Plots – Python

Just a very quick and dirty reminder of how to do this, starting with a data frame.

Most of the info in this port can be found here.

# import all the stuff we need
import pandas as pd
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

We can load the data frame (its a csv file) and check the data

df_data = pd.read_csv('my_awesome_data.csv')
print df_data

That should return

       date  cor  mid  per   cor_pec   mid_pec   per_pec
0   2012-01   64   22   21  0.039482  0.013033  0.012507  
1   2012-02   54   56   40  0.033313  0.033175  0.023824  
2   2012-03   42   79   20  0.025910  0.046801  0.011912  
3   2012-04   95   56   12  0.058606  0.033175  0.007147  
4   2012-05  213  151  131  0.131400  0.089455  0.078023  
...    ...    ...    ...    ...
...    ...    ...    ...    ...
19  2013-08   67  104  227  0.041333  0.061611  0.135200  
20  2013-09   65   97  153  0.040099  0.057464  0.091126  
21  2013-10   69   54   97  0.042566  0.031991  0.057772  
22  2013-11   41   37   65  0.025293  0.021919  0.038714  
23  2013-12   10    2   27  0.006169  0.001185  0.016081

The ones we want to plot are the 3 *_pec values, which will be our y values.
We also want to create the x values

# x values
x_ax = np.lispace(0,23,24)

# now for each of the y values
y_cor = df_data['cor_pec']
y_mid = df_data['mid_pec']
y_per = df_data['per_pec']

If we were to plot these…

plt.figure()
plt.axis([0, int_x_points-1, 0, .145])

plt.plot(x_ax, y_cor,
         x_ax, y_mid,
         x_ax, y_per)

plt.xticks(x_ax, df_data['date'], size='small', rotation=70)
plt.tight_layout()
plt.savefig('normal_plot.png')

… we would get something like this.

normal_plot

Which is fine, but we want smooth lines, so we need to change both x and y values

# new x values
xn_ax = np.linspace(0,24,24*10)

# new y values
yn_cor = interp1d(x_ax, y_cor, kind='cubic')
yn_mid = interp1d(x_ax, y_mid, kind='cubic')
yn_per = interp1d(x_ax, y_per, kind='cubic')

So if we plot the graph with these new values…

plt.figure()
plt.axis([0, int_x_points-1, 0, .145])

plt.plot(xn_ax, yn_cor(xn_ax),
         xn_ax, yn_mid(xn_ax),
         xn_ax, yn_per(xn_ax))

plt.xticks(x_ax, df_data['date'], size='small', rotation=70)
plt.tight_layout()
plt.savefig('smooth_plot.png')

… it will look like this

smooth_plot

One reply on “Smooth Line Plots – Python”

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s