How can I plot a broken list, so that at the end of the first part I can continue starting the next part, with a different color on the line?

Question:

I’m trying to plot a list from the data, but I need to slice the list and show the result in two moments, each one interpreted by a different color on the plot. As per the code below, if I try to put each part of the list on a plot, I have an overlap in the construction of the image. How to solve the continuity of the second plot in relation to the first?

import matplotlib.pyplot as plt

lst = [5,10,15,8,9,6,8,12,13,6]

plt.plot(lst[:5])
plt.plot(lst[7:],color='red') #I would like to continue from the plot of the previous line
plt.show()

plot

I hope to use the code to identify distinct moments in the data.

Asked By: Mirkos M.

||

Answers:

Like fdireito says, if you want your data to be plotted in a different location with respect to the x-axis, you need to provide x data.

Documentation on the plt.plot() method shows that you can just provide the x data as a optional first argument. By default the method uses the index position of each data point as x argument.

To make the second plot align with the first plot, you need to tell the plot method which x arguments to use. In your case you want x to continue counting from 4, since you plot the first 5 elements of lst on the first line.

This is what your code could look like:

import matplotlib.pyplot as plt

lst = [5,10,15,8,9,6,8,12,13,6]

plt.plot(lst[:5])
plt.plot(range(4, 4+len(lst[7:])), lst[7:], color='red') # Range starts at 4 because the first plot ends at index 4.
plt.show()
Answered By: Bram van Asseldonk
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.