gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:28:05 24 4
gpt4 key购买 nike

我正在使用 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)

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

enter image description here

提前致谢。

最佳答案

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

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

enter image description here

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

关于python - 如何在 Matplotlib 图中的一行中获得不同的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38051922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com