python - 根据 Matplotlib 中的 y 值使线图的某些部分具有不同的颜色
问题描述
我正在制作一个程序,它采用随机数据列表并将其绘制出来。如果它超过某个值,我希望图表的颜色发生变化。
https://matplotlib.org/gallery/lines_bars_and_markers/multicolored_line.html Matplotlib 有一个关于这样做的条目,但它似乎需要使用函数作为不使用列表的图形的输入。
有谁知道如何将其转换为适用于列表或其他方式?
到目前为止,这是我的代码(没有我可怕的失败尝试对它们进行颜色编码)
from matplotlib import pyplot as plt
import random
import sys
import numpy as np
#setting the max and min values where I want the colour to change
A_min = 2
B_max = 28
#makes lists for later
A_min_lin = []
B_max_lin = []
#simulating a corruption of the data where it returns all zeros
sim_crpt = random.randint(0,10)
print(sim_crpt)
randomy = []
if sim_crpt == 0:
randomy = []
#making the empty lists for corrupted data
for i in range(0,20):
randomy.append(0)
print(randomy)
else:
#making a random set of values for the y axis
for i in range(0,20):
n = random.randint(0,30)
randomy.append(n)
print(randomy)
#making an x axis for time
time = t = np.arange(0, 20, 1)
#Making a list to plot a straight line showing where the maximum and minimum values
for i in range(0, len(time)):
A_min_lin.append(A_min)
B_max_lin.append(B_max)
#Testing to see if more than 5 y values are zero to return if it's corrupted
tracker = 0
for i in (randomy):
if i == 0:
tracker += 1
if tracker > 5:
sys.exit("Error, no data")
#ploting and showing the different graphs
plt.plot(time,randomy)
plt.plot(time,A_min_lin)
plt.plot(time,B_max_lin)
plt.legend(['Data', 'Minimum for linear', "Maximum for linear"])
plt.show
解决方案
您可以使用np.interp
生成细粒度数据来绘制:
# fine grain time
new_time = np.linspace(time.min(), time.max(), 1000)
# interpolate the y values
new_randomy = np.interp(new_time, time, randomy)
# this is copied from the link with few modification
points = np.array([new_time, new_randomy]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
fig, axs = plt.subplots()
norm = plt.Normalize(new_randomy.min(), new_randomy.max())
lc = LineCollection(segments, cmap='viridis', norm=norm)
# Set the values used for colormapping
lc.set_array(new_randomy[1:])
lc.set_linewidth(2)
line = axs.add_collection(lc)
fig.colorbar(line, ax=axs)
# set the limits
axs.set_xlim(new_time.min(), new_time.max())
axs.set_ylim(new_randomy.min(), new_randomy.max())
plt.show()
输出:
推荐阅读
- java - 在不同的 chrome 选项卡中运行测试方法
- matplotlib - 根据列中的值使用 matplotlib 生成图例
- ms-access - 比较 Access 查询中的 2 个以上字段
- c++ - C ++中线程中带有while循环的条件变量
- android - 动态获取 XML 中的应用程序 ID
- reactjs - 如何将文件附件按钮更改为发送消息“重置”的重置按钮
- python - 查找与文档中单词出现相关的单词频率
- sql-server - 获取状态变化数据
- xamarin - 检查本地通知的 NSDictionary 中是否存在值
- php - 无法创建 index.html 文件 - TimThumb