1

i got two lists and I am trying to plot the 5 values as a red line and the 0 as a blue line at a fixed y-value. My lists are similar to these two:

main_list = [5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 0, 0, 5, 0, 0]
x_axis = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

I tried to get this output so i could plot each sub-list as a new plot with either the color red for 5 and color blue for 0:

main_list = [[5, 5, 5, 5, 5, 5], [0, 0, 0, 0], [5, 5, 5, 5, 5, 5], [0, 0],[5],[0, 0]]

I have tried the following but I cant seem to get the correct output. I have the feeling that my approach is wrong but I cant think of a different solution.

def split_list(list):
  main_list = [[i] for i in list]
  for i,sub_list in enumerate(main_list):
    if(i<len(main_list)-1):
     if(sub_list[0]==main_list[i+1][0]):
      main_list[i+1] = sub_list+ main_list[i+1] 
      del main_list[i]
  return main_list 

but my output is :

main_list = [[5, 5], [5, 5], [5, 5], [0, 0], [0, 0], [5, 5], [5, 5], [5, 5], [0, 0], [5], [0, 0]]

1 Answer 1

2

splitting the data

easy version: y-data only

An easy way to split the list like you want is to use itertools.groupby:

from itertools import groupby
ys = [list(g) for k,g in groupby(main_list)]

output:

>>> ys
[[5, 5, 5, 5, 5, 5], [0, 0, 0, 0], [5, 5, 5, 5, 5, 5], [0, 0], [5], [0, 0]]
combined x and y

Now it gets slightly more complex if you want to align the two lists. You can use zip:

[list(zip(*g)) for k,g in groupby(zip(x_axis, main_list), lambda x: x[1])]

output:

[[(0, 1, 2, 3, 4, 5), (5, 5, 5, 5, 5, 5)],
 [(6, 7, 8, 9), (0, 0, 0, 0)],
 [(10, 11, 12, 13, 14, 15), (5, 5, 5, 5, 5, 5)],
 [(16, 17), (0, 0)],
 [(18,), (5,)],
 [(19, 20), (0, 0)]]

If you prefer to have two output lists, you can do:

xs, ys = list(zip(*(list(zip(*g)) for k,g in groupby(zip(x_axis, main_list), lambda x: x[1]))))

output:

>>> xs
((0, 1, 2, 3, 4, 5),
 (6, 7, 8, 9),
 (10, 11, 12, 13, 14, 15),
 (16, 17),
 (18,),
 (19, 20))

>>> ys
 ((5, 5, 5, 5, 5, 5), (0, 0, 0, 0), (5, 5, 5, 5, 5, 5), (0, 0), (5,), (0, 0)))

plotting

import matplotlib.pyplot as plt

groups = (list(zip(*g)) for k,g in groupby(zip(x_axis, main_list), lambda x: x[1]))

colors = {0: 'blue', 5: 'red'}
ax = plt.subplot()
for x,y in groups:
    ax.plot(x, y, marker='o', c=colors[y[0]])

output:

broken plot

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.