numpy 如何根据另一个变量更改单线图的颜色

hts6caw3  于 2023-08-05  发布在  其他
关注(0)|答案(2)|浏览(85)

我想用下面的公式画一条线。
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()

字符串



但它绘制了两条不同的线。你知道吗?

5tmbdcev

5tmbdcev1#

请注意,plt.plot处理点,而您希望为连接这些点的线段着色。因此,您的调用plt.plot(x_positive_slope, y_positive_slope, ...)只是连接具有正斜率的线段的所有起点。
您可以应用教程中的"multicolored line"方法。它将连续曲线转换为短段,并通过颜色Map表为每个段着色。

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import numpy as np

x = np.arange(51)
ε = np.random.randn(x.size)
y = x * (1 + 0.25 * ε)
segments = np.c_[x[:-1], y[:-1], x[1:], y[1:]].reshape(-1, 2, 2)
slope = np.diff(y)
lc = LineCollection(segments, cmap='RdYlBu')
lc.set_array(slope > 0)
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.set_xlim(x.min(), x.max())
ax.set_ylim(y.min(), y.max())
plt.show()

字符串


的数据

g6baxovj

g6baxovj2#

import numpy as np
import matplotlib.pyplot as plt

N = 100  # Change the number of data points to 100
x = np.arange(N)  
epsilon = np.random.rand(N)  # Generate random noise for N data points
y = x * (1 + 0.25 * epsilon)  # Calculate y with noise
slope = np.diff(y)  # Calculate the slope of y with respect to x

negative = slope < 0
positive = ~negative

xx = np.array([x[:-1], x[1:]])
yy = np.array([y[:-1], y[1:]])

xp = xx[:, positive]
yp = yy[:, positive]

xn = xx[:, negative]
yn = yy[:, negative]

plt.figure(figsize=(10, 4))
first_positive_line, *_ = plt.plot(xp, yp, c='b')
first_negative_line, *_ = plt.plot(xn, yn, c='r')

plt.legend([first_positive_line, first_negative_line], 
           ['Positive Slope', 'Negative Slope'])

plt.xlabel('x')
plt.ylabel('y')
plt.title('Line Plot with Color Trend Following Slope')
plt.grid(True)
plt.show()

字符串


的数据

相关问题