Search code examples
pythonnumpymatplotlibgraphsmoothing

smooth line matplotlib: How can i smooth line with 5 points of sample?


hope you are fine, i have the next question:

suppose i have 2 list with values x=mode, y=floor; my question is how can i join the points with smooth line using just 5 points:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import savgol_filter
from scipy.optimize import curve_fit
from scipy import interpolate

mode=[0.0, -0.000906168, -0.000466564, 0.000320168, 0.000800825]
floor=[0, 3.2, 6.4, 9.6, 12.8]

plt.plot(mode1,floor,'green')
plt.plot(mode1,floor,'o')
plt.plot(np.repeat(0,len(floor)),floor,'o')
plt.plot(np.repeat(0,len(floor)),floor,'black')
plt.show()

the green plot is the line that i would like to have in smooth way, i was trying fitting with all libraries that you saw in the import but they don't bring me the good smooth, please i appreciate your helping.


Solution

  • Scipy's interpolate.interp1d with either kind='cubic' or kind='quadratic' can be used to create a smooth curve. A quadratic curve looks a bit stiffer than a cubic. Note that in the example x and y are reversed to how they're usually drawn.

    Here is some example code to demonstrate how such an interpolation can be used in your situation:

    import matplotlib.pyplot as plt
    import numpy as np
    from scipy import interpolate
    
    mode = [0.0, -0.000906168, -0.000466564, 0.000320168, 0.000800825]
    floor = [0, 3.2, 6.4, 9.6, 12.8]
    
    plt.plot(mode, floor, marker='o', markerfacecolor='dodgerblue', markeredgecolor='dodgerblue',
             linestyle='dotted', color='limegreen', linewidth=1)
    plt.plot(np.zeros(len(floor)), floor, marker='o', markerfacecolor='orange', markeredgecolor='orange',
             linestyle='solid', color='purple')
    
    smoothed_mode = interpolate.interp1d(floor, mode, 'cubic')
    floor_range = np.linspace(min(floor), max(floor), 500)
    plt.plot(smoothed_mode(floor_range), floor_range, ls='solid', color='crimson')
    
    plt.show()
    

    resulting plot