Python Forum
How to plot two list on the same graph with different colors? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to plot two list on the same graph with different colors? (/thread-4025.html)



How to plot two list on the same graph with different colors? - Alberto - Jul-18-2017

Dear Python Users,

I tried to plot a graph from two lists on the same graph. However, what I get is that two lists are plotted against each other. How can I plot two lists on the same graph, but with different colors?


import matplotlib.pyplot as plt

train_W = [1,2,3,4,5,6]
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()



RE: How to plot two list on the same graph with different colors? - MTVDNA - Jul-18-2017

If you submit two arrays as arguments, it is assumed that they are x-coordinates and y-coordinates respectively. If you use only one array, these values will be used as y-coordinates and the x-coordinates will be [0, 1, 2, ...].

You have multiple options to plot more than one function.

You can submit x and y values for each graph you want to plot:
x_list = range(6)
plt.plot(x_list, forecast, x_list, train_W, x_list, train_Z)
The colors of the lines will be different by default, but if you want to set them manually you could do that like this:
plt.plot(x_list, forecast, 'r-.', x_list, train_W, 'bx', x_list, train_Z, 'y')
But imho this code is not very easy to read. (note that 'r-.' means a dashed red line, 'bx' means blue 'x' markers with no line)

Note that the length of the arrays must be equal, or you'll run into e.g.:
Error:
ValueError: x and y must have same first dimension, but have shapes (6,) and (5,)
Also, if you want to apply other keyword arguments to the plot they'll apply to each of those lines:
plt.plot(x_list, forecast, x_list, train_W, x_list, train_Z, label='test')
plt.legend()
plt.show()
Each line in this plot will have the same entry in the in the legend.


That's why I prefer method 2: calling plot() separately for each line:
plt.plot(forecast)
plt.plot(train_Z)
plt.show()
or with x-values explicitly included:
plt.plot(x_list, forecast)
plt.plot(x_list, train_Z)
plt.show()
or with different keyword arguments for each line
plt.plot(x_list, forecast, label='forecast')
plt.plot(x_list, train_Z, label='train Z')
plt.legend()
plt.show()
You can find more info about how to use arguments for plot here: https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot


RE: How to plot two list on the same graph with different colors? - Alberto - Jul-18-2017

Thank you!