python data scaling

Many times we want to draw a graph of a data. The shape of the graph of this data is what we need, but the scale of the y-axis is wrong. It may be larger or smaller. We want not to change the distribution and shape of the data. The situation of the graph drawn Next, to scale this data to a certain extent, you can follow the following method.


first import the package

import numpy as np
import matplotlib.pyplot as plt

We first generate a set of data

# 生成y的值
x = np.linspace(-5, 5, 100)
y = 2 * x**3 - 3 * x**2 + 4 * x + 1
# 加噪声
noise = np.random.normal(0, 10, size=y.shape)
y_noisy = y + noise
# 绘制图形
plt.figure(figsize=(7,3))
plt.plot(y_noisy)
plt.show()

You can see a line chart of the data, which looks like this. Then check its value range

y_noisy.min(),y_noisy.max()

 

In the case of the minimum and maximum values, y is in this interval, and then we need to map it to another interval.


 mapping formula

gpt told me, it was right, and then I changed the code he wrote to become the following scaling function.

def Linear_transformation(y,interval=[-3,3]):
    y=np.array(y)
    y_min = y.min()  ;  y_max = y.max()
    a = interval[0]  ;  b = interval[-1]
    y_new = (b-a)*(y-y_min)/(y_max-y_min)+a
    return y_new

 # Assume y is to be mapped to (-5,5)

y_new=Linear_transformation(y_noisy,interval=[-5,5])
y_new

drawing view 

plt.figure(figsize=(7,3))
plt.plot(y_new)
plt.show()

 

 It can be clearly seen that the shape of the data is exactly the same as the original, but the y-axis has changed, and it has become in the interval from -5 to 5.

It is also possible to zoom in if you want, for example, zoom in to -1000 to 1000

plt.figure(figsize=(7,3))
plt.plot(Linear_transformation(y_noisy,interval=[-1000,1000]))
plt.show()

very useful. In this way, you no longer have to worry about the wrong data range when drawing pictures... 

Guess you like

Origin blog.csdn.net/weixin_46277779/article/details/130248107