7

I need to plot two lists on the same graph. The lines should be of different colors.

I am trying to plot forecast and train_Z on the same graph, but I get them plotted against each other, with forecast on the x-axis, and train_Z on the y-axis.

Here is the code I tried:

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

With alpha == 5

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Alberto Alvarez
  • 805
  • 3
  • 11
  • 20

4 Answers4

8

You should use plt.plot twice to plot two lines.

I don't know what is your X axis but obviously you should create another array/list to be your X value.

Then use plt.plot(x_value,forecast, c='color-you-want') and plt.plot(x_value,train_z, c='another-color-you-want').

. Please refer to the pyplot documentation for more details.

Kye
  • 4,279
  • 3
  • 21
  • 49
Anna Yu
  • 81
  • 1
7

As per the matplotlib.pyplot.plot, plot multiple sets with [x], y, [fmt]. If y is passed without a corresponding x, then y will be plotted sequentially against range(len(y)).

Scatter Plot

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

Line Plot

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

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
subrata
  • 111
  • 3
  • 8
0

Stealing Borrowing from another answer, this appears to work:

# 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

other answer: python/matplotlib - multicolor line

Of course, replace the 'r', 'g', 'b' values with any others in https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot colors list

-1
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")
krishna
  • 1
  • 2