简体   繁体   中英

How to smooth this Figure in Python with from scipy.interpolate import make_interp_spline

There is a plot which I want to make smooth for better representation. I tried scipy.interpolate , however it produced this error:

raise ValueError("Expect x to be a 1-D sorted array_like.") ValueError: Expect x to be a 1-D sorted array_like.

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

    startnm = 550
    endnm = 700
    y = np.empty((10,))

    for aci in range(0, 91, 10):

    data = pd.read_csv(f".\\30mg-ml-PSQD-withZNO-12-nov-21\\{aci}.txt",
                       delimiter="\t") .to_numpy()[:, [0, 1]]
    print(type(data[0, 0]))
    starti, endi = 0, 0
    for i in range(len(data[:, 0])):
        if startnm < float(data[i, 0]) and starti == 0:
            starti = i
        elif endnm < float(data[i, 0]) and endi == 0:
            endi = i
            break

    y[aci//10] = np.sum(data[starti:endi, 1])


    theta = np.linspace(0, np.pi, 19)

    output = []
    x = []
    for i in range(10):
    temp0 = y[i]
    output.append(temp0*np.cos(theta[i])/y.max())
    x.append(temp0*np.sin(theta[i])/y.max())
    pass

    print(output)
    print(x)


    plt.title("title")
    plt.xlabel("x")
    plt.ylabel("y")

    plt.plot(x, output,"--")
    plt.plot(-np.array(x), output, "--")

    x = np.sin(theta)*np.cos(theta)
    y = np.cos(theta)*np.cos(theta)


    plt.plot(x, y, "r")
    plt.grid(color = 'green', linestyle = '--', linewidth = 0.5)

 

    plt.show()

I want to smooth this graph as much as possible. How can I do it?

我想让虚线尽可能平滑

The error just tells you that the x array needs to be sorted. Note also that make_interp_spline does not do any smoothing. For that, use splrep .

My friend's solution to this problem:

from scipy.interpolate import interp1d

f1 = interp1d(list(range(10)), x, kind="quadratic")
f2 = interp1d(list(range(10)), output, kind="quadratic")

xnew = f1(np.linspace(0, 8.9, 100))    
outnew = f2(np.linspace(0, 8.9, 100))




plt.plot(xnew, outnew)
plt.plot(-xnew, outnew, "b")

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM