Home > other >  How can I plot a broken list, so that at the end of the first part I can continue starting the next
How can I plot a broken list, so that at the end of the first part I can continue starting the next

Time:12-17

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.

CodePudding user response:

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