How to smooth lines in a figure in python?

12,027

You should apply interpolation on your data and it shouldn't be "linear". Here I applied the "cubic" interpolation using scipy's interp1d. Also, note that for using cubic interpolation your data should have at least 4 points. So I added another year 2031 and another value too all weights (I got the new weight value by subtracting 1 from the last value of weights):

Here's the code:

import matplotlib.pyplot as plt
import pandas as pd
from scipy.interpolate import interp1d
import numpy as np

# df['year'] = ['2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030']
# df['name'] = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
# df['weight'] = [80, 65, 88, 65, 60, 70, 60, 55, 65]

df1 = pd.DataFrame()
df1['Weight_A'] = [80, 65,  60 ,59]
df1['Weight_B'] = [65, 60,  55 ,54]
df1['Weight_C'] = [88, 70,  65 ,64]
df1.index = [2005,2015,2030,2031]


ax = df1.plot.line()
ax.set_title('Before interpolation')
ax.set_xlabel("year")
ax.set_ylabel("weight")

f1 = interp1d(df1.index, df1['Weight_A'],kind='cubic')
f2 = interp1d(df1.index, df1['Weight_B'],kind='cubic')
f3 = interp1d(df1.index, df1['Weight_C'],kind='cubic')

df2 = pd.DataFrame()
new_index = np.arange(2005,2031)
df2['Weight_A'] = f1(new_index)
df2['Weight_B'] = f2(new_index)
df2['Weight_C'] = f3(new_index)
df2.index = new_index

ax2 = df2.plot.line()
ax2.set_title('After interpolation')
ax2.set_xlabel("year")
ax2.set_ylabel("weight")


plt.show()

And the results:

Before interpolation After interpolation

Share:
12,027
Jolie
Author by

Jolie

Updated on July 24, 2022

Comments

  • Jolie
    Jolie almost 2 years

    So with the code below I can plot a figure with 3 lines, but they are angular. Is it possible to smooth the lines?

    import matplotlib.pyplot as plt
    import pandas as pd
    
    # Dataframe consist of 3 columns
    df['year'] = ['2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030']
    df['name'] = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
    df['weight'] = [80, 65, 88, 65, 60, 70, 60, 55, 65]
    fig,ax = plt.subplots()
    
    # plot figure to see how the weight develops through the years
    for name in ['A','B','C']:
        ax.plot(df[df.name==name].year,df[df.name==name].weight,label=name)
    
    ax.set_xlabel("year")
    ax.set_ylabel("weight")
    ax.legend(loc='best')
    
  • Jolie
    Jolie over 7 years
    woow thanks you so much!! I tried to smooth the lines almost a whole day and just give up. Finally I just put extra point between every data to smooth it a little bit. Your code helps me a lot, thanks!!
  • Kennet Celeste
    Kennet Celeste over 7 years
    @Jolie no problem :)