如何在同一张图中绘制两个列表,使用不同的颜色。

7

我需要在同一张图上绘制两个列表,线条颜色应该不同。

我正在尝试在同一张图上绘制forecasttrain_Z,但是它们被绘制成相互对立的形式,forecast在x轴上,train_Z在y轴上。

这是我尝试过的代码:

import matplotlib.pyplot as plt 

train_X = [1,2,3,4,5] 
train_Y = [10, 20, 30, 40, 50] 
train_Z = [10, 20, 30, 40, 50,25] 
alpha = float(input("Input alpha: ")) 
forecast = []

for x in range(0, len(train_X)+1):  
    if x==0:       
        forecast.append(train_Y[0])  
    else:  
        forecast.append(alpha*train_Y[x-1] + (1 - alpha) * forecast[x-1])
plt.plot(forecast,train_Z,'g') 
plt.show()

使用 alpha == 5

enter image description here


你有什么问题需要问吗?你只得到了一行还是两行,而且它们的颜色都相同吗? - Alexander Higgins
你有没有尝试自己寻找答案?只需要查看matplotlib文档,就能非常容易地找到如何在一个图表上绘制两条线的方法。 - jacoblaw
谢谢您的回答。我只得到了一行... - Alberto Alvarez
在你目前的代码中,我只看到了一个plt.plot()命令。你要绘制的第二条线是什么? - Kevin
我正在尝试在同一张图上绘制预测和train_Z,但是我得到的结果是它们相互绘制。(预测 - X轴,train_Z - y轴) - Alberto Alvarez
4个回答

9

你需要使用 plt.plot 两次来绘制两条线。

我不知道你的X轴是什么,但很明显你应该创建另一个数组/列表作为你的X值。

然后使用 plt.plot(x_value,forecast, c='你想要的颜色')plt.plot(x_value,train_z, c='另一种你想要的颜色')

请参考pyplot文档获取更多信息。


8
根据{{link1:matplotlib.pyplot.plot}},使用[x],y,[fmt]绘制多个数据集。如果传递了没有对应的xy,那么y将按顺序绘制在range(len(y))上。

散点图

import matplotlib.pyplot as plt

y1 = [1,2,3,4,12,15]
y2 = [1,4,9,16]

plt.plot(y1, 'g*', y2, 'ro')
plt.show()

enter image description here

折线图

plt.plot(y1, 'g', y2, 'r')
plt.show()

enter image description here


0

Stealing 从另一个答案中借鉴,似乎这个方法有效:

# plt.plot(forecast,train_Z,'g') # replace this line, with the following for loop

for x1, x2, y1,y2 in zip(forecast, forecast[1:], train_Z, train_Z[1:]):
    if y1 > y2:
        plt.plot([x1, x2], [y1, y2], 'r')
    elif y1 < y2:
        plt.plot([x1, x2], [y1, y2], 'g')
    else:
        plt.plot([x1, x2], [y1, y2], 'b') # only visible if slope is zero

plt.show()

enter image description here

其他答案:Python/Matplotlib-多彩线

当然,你可以用 https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot 中的颜色列表替换'r''g''b'的值。


-2
plt.plot([1,2,3,4,5,6,7,8,9],[9,8,7,6,5,4,3,2,1])
plt.plot([1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8]) #these combination in plot one
plt.title("First plot")


plt.figure()

plt.plot([1,2,3,4,5,6,7,8,9],[9,8,7,6,5,4,3,2,1])
plt.plot([1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8])# it is plotted in second plot
plt.title("second plot")

这并没有回答问题。 - Trenton McKinney
现在它们只是使用不同的输入,您现在可以检查。 - krishna
我投票删除这个问题,因为它与这个答案相同。请不要添加谢谢确认的回答。一旦你通过质量贡献获得足够的声望,你就可以对你认为有帮助的问题和答案进行投票 - undefined
这与这个答案相同,只是将变量名替换为列表。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接