Skip to main content
 首页 » 编程设计

python之如何在 Matplotlib 图中的一行中获得不同的颜色

2025年04月02日12duanxz

我正在使用 matplotlib 来创建绘图。我必须在图表中画一条线,必须根据每个点的函数定义颜色。例如,我需要一条线,其中 2000 以下的点涂成红色,2000 以上的点涂成蓝色。我怎样才能得到这个?您是否知道实现它的类似解决方案或解决方法?

这是我的示例代码,它将孔线涂成蓝色(我猜是默认颜色)

def draw_curve(points, labels):      
 
    plt.figure(figsize=(12, 4), dpi=200) 
 
    plt.plot(labels,points) 
 
    filename = "filename.png" 
 
    plt.savefig("tmp/{0}".format(filename))  
 
    figure = plt.figure() 
 
    plt.close(figure) 

因此,在下图中,我希望浅蓝色水平线上方的值与下方值的颜色不同。

提前致谢。

请您参考如下方法:

你必须给每一段线涂上颜色:

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib.collections import LineCollection 
from matplotlib.colors import ListedColormap, BoundaryNorm 
 
# my func 
x = np.linspace(0, 2 * np.pi, 100) 
y = 3000 * np.sin(x) 
 
# select how to color 
cmap = ListedColormap(['r','b']) 
norm = BoundaryNorm([2000,], cmap.N) 
 
# get segments 
xy = np.array([x, y]).T.reshape(-1, 1, 2) 
segments = np.hstack([xy[:-1], xy[1:]]) 
 
# make line collection 
lc = LineCollection(segments, cmap = cmap, norm = norm) 
lc.set_array(y) 
 
# plot 
fig, ax = plt.subplots() 
ax.add_collection(lc) 
ax.autoscale() 
plt.show() 

此处有更多示例:http://matplotlib.org/examples/pylab_examples/multicolored_line.html