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

huangapple go评论91阅读模式
英文:

How to change the color of a single line plot based on another variable

问题

我想要使用以下方程绘制一条线。

y = x(1+0.25ε)
其中,
x = {0, 1, 2, ..., 200}
ε = np.random.randn()

并且我想要根据斜率更改绘图的颜色。即当斜率为正时应为蓝色,当斜率为负时应为红色。就像下面这样

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

import matplotlib.pyplot as plt
import numpy as np

N = 100  # 将数据点数量更改为100
x = np.array([i for i in range(N)])  # 使用x=[i for i in range(100)]
epsilon = np.random.rand(N)  # 为N个数据点生成随机噪声
y = x * (1 + 0.25 * epsilon)  # 计算带有噪声的y
slope = np.gradient(y, x)  # 计算y相对于x的斜率

# 根据条件分离数据点(斜率 > 0)
positive_slope = slope > 0
x_positive_slope = x[positive_slope]
y_positive_slope = y[positive_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()

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

但它绘制了两条不同的线。有什么想法?

英文:

I want to plot a line using the following equation.

y = x(1+0.25ε)
Where,
x = {0, 1, 2, ..., 200}
ε = np.random.randn()

And i want to change the color of the plot based on slop. I.e it should be blue when the slope is positive and it should be red when slope is negative. Like the following

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

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 &gt; 0)
positive_slope = slope &gt; 0
x_positive_slope = x[positive_slope]
y_positive_slope = y[positive_slope]

# Separate the data points based on the condition (slope &lt; 0)
negative_slope = slope &lt; 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=&#39;r&#39;, label=&#39;Positive Slope&#39;)
plt.plot(x_negative_slope, y_negative_slope, color=&#39;b&#39;, label=&#39;Negative Slope&#39;)
plt.legend()
plt.xlabel(&#39;x&#39;)
plt.ylabel(&#39;y&#39;)
plt.title(&#39;Line Plot with Color Trend Following Slope&#39;)
plt.grid(True)
plt.show()

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

but it plots two different lines. Any idea ?

答案1

得分: 2

请注意,plt.plot 用于绘制点,而你想要着色连接这些点的线段。因此,你的调用 plt.plot(x_positive_slope, y_positive_slope, ...) 简单地连接了所有斜率为正的线段的起始点。

你可以应用教程中的"多彩线段"方法。它将连续曲线转换为短线段,并通过色彩图为每个线段着色。

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()

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

英文:

Note that plt.plot works with points, while you want to color the line segments which connect these points. As such, your call plt.plot(x_positive_slope, y_positive_slope, ...) simply connects all starting points of line segments with positive slope.

You can apply the "multicolored line" approach from the tutorial. It converts the continuous curve into short segments, and colors each segment via a colormap.

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=&#39;RdYlBu&#39;)
lc.set_array(slope &gt; 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()

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

答案2

得分: 1

import numpy as np
import matplotlib.pyplot as plt

N = 100  # 将数据点数量更改为100
x = np.arange(N)
epsilon = np.random.rand(N)  # 为N个数据点生成随机噪声
y = x * (1 + 0.25 * epsilon)  # 使用噪声计算y值
slope = np.diff(y)  # 计算y相对于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],
           ['正斜率', '负斜率'])

plt.xlabel('x')
plt.ylabel('y')
plt.title('带有斜率趋势的线图')
plt.grid(True)
plt.show()

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

英文:
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 &lt; 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=&#39;b&#39;)
first_negative_line, *_ = plt.plot(xn, yn, c=&#39;r&#39;)

plt.legend([first_positive_line, first_negative_line], 
           [&#39;Positive Slope&#39;, &#39;Negative Slope&#39;])

plt.xlabel(&#39;x&#39;)
plt.ylabel(&#39;y&#39;)
plt.title(&#39;Line Plot with Color Trend Following Slope&#39;)
plt.grid(True)
plt.show()

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

huangapple
  • 本文由 发表于 2023年7月23日 20:25:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76748224.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定