When plotting multiple lines in Matplotlib, does each need to have the same number of x and y values?


#1

Question

In the context of this exercise, when plotting multiple lines in Matplotlib, does each line need to have the same number of x and y values?

Answer

No, when you are plotting multiple lines, they do not need to have the same amount of x and y values, nor do they need to share the same x values.

When you plot multiple lines, it is as though each line is plotted separately onto the same graph.

For example, the following code will draw two lines on a single plot. The first line will be drawn on the x coordinates 0 to 4, while the second line will be drawn over the x coordinates 5 to 8. The second line will also have one less value than the first line.

Example

x1 = [0, 1, 2, 3, 4]
x2 = [5, 6, 7, 8]

y1 = [100, 200, 300, 400, 500]
y2 = [100, 200, 300, 400]

plt.plot(x1, y1)
plt.plot(x2, y2)

plt.show()