gpt4 book ai didi

python - 如果 y 值更改,如何更改线条颜色

转载 作者:太空宇宙 更新时间:2023-11-03 11:23:39 25 4
gpt4 key购买 nike

我正在使用 pylab 绘制一些图表假设我想绘制这个:

x = [0,1,2,3,4,5,6,7,8,9,10]
y = [0,0,0,1,1,0,0,1,0,0,0]

plt.plot(x,y,'g')
plt.show()

但每次 [y = 1] 我都想将线条的颜色更改为红色。

这可能吗?

Sketch of what I want to accomplish

最佳答案

灵感来自 this answer :

from matplotlib import collections  as mc
from matplotlib import pyplot as plt

x = [0,1,2,3,4,5,6,7,8,9,10]
y = [0,0,0,1,1,0,0,1,0,0,0]

def getLines(points):
lines = []
lastX, lastY = points[0]
for x,y in points[1:]:
lines.append([(lastX,lastY), (lastX+1,lastY)])
if y!=lastY:
lines.append( [(x, lastY), (x,y)] )
lastX, lastY = (x,y)
return lines

def getColor(point0, point1):
x0,y0 = point0
x1,y1 = point1
return "r" if (y1==y0) and (y1==1) else "g"

points = [(i,j) for i,j in zip(x,y)]
lines = getLines(points)
colors = [getColor(*line) for line in lines]


lc = mc.LineCollection(lines, colors=colors, linewidths=2)
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)

输出:

enter image description here

关于python - 如果 y 值更改,如何更改线条颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37967521/

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