我想用下面的公式画一条线。
y = x(1+0.25ε)其中,x = {0,1,2,...,200} ε = np·random·randn()
我想根据坡度改变图的颜色。也就是说,当斜率为正时,它应该是蓝色的,当斜率为负时,它应该是红色的。像下面这样
x1c 0d1x的数据
import numpy as np
N = 100 # Change the number of data points to 100
x = np.array([i for i in range(N)]) # Use x=[i for i in range(100)]
epsilon = np.random.rand(N) # Generate random noise for N data points
y = x * (1 + 0.25 * epsilon) # Calculate y with noise
slope = np.gradient(y, x) # Calculate the slope of y with respect to x
# Separate the data points based on the condition (slope > 0)
positive_slope = slope > 0
x_positive_slope = x[positive_slope]
y_positive_slope = y[positive_slope]
# Separate the data points based on the condition (slope < 0)
negative_slope = slope < 0
x_negative_slope = x[negative_slope]
y_negative_slope = y[negative_slope]
plt.figure(figsize=(10, 4))
plt.plot(x_positive_slope, y_positive_slope, color='r', label='Positive Slope')
plt.plot(x_negative_slope, y_negative_slope, color='b', label='Negative Slope')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Line Plot with Color Trend Following Slope')
plt.grid(True)
plt.show()
字符串
的
但它绘制了两条不同的线。你知道吗?
2条答案
按热度按时间5tmbdcev1#
请注意,
plt.plot
处理点,而您希望为连接这些点的线段着色。因此,您的调用plt.plot(x_positive_slope, y_positive_slope, ...)
只是连接具有正斜率的线段的所有起点。您可以应用教程中的"multicolored line"方法。它将连续曲线转换为短段,并通过颜色Map表为每个段着色。
字符串
的数据
g6baxovj2#
字符串
的数据