Quantifeye
Quantifeye

Reputation: 261

python multiple lines as one group

If I plot various disjoint lines with one call as follows...

>>> import matplotlib.pyplot as plt
>>> x = [random.randint(0,9) for i in range(10)]
>>> y = [random.randint(0,9) for i in range(10)]
>>> data = []
>>> for i in range(0,10,2):
...     data.append((x[i], x[i+1]))
...     data.append((y[i], y[i+1]))
... 
>>> print(data)
[(6, 4), (4, 3), (6, 5), (0, 4), (0, 0), (2, 2), (2, 0), (6, 5), (2, 5), (3, 6)]
>>> plt.plot(*data)
[<matplotlib.lines.Line2D object at 0x0000022A20046E48>, <matplotlib.lines.Line2D object at 0x0000022A2004D048>, <matplotlib.lines.Line2D object at 0x0000022A2004D9B0>, <matplotlib.lines.Line2D object at 0x0000022A20053208>, <matplotlib.lines.Line2D object at 0x0000022A20053A20>]
>>> plt.show()

enter image description here

I cant figure out how to I get python/matplotlib to see it as a single plot, of the same color, linewidth, ect and the same legend entry...

thank you in advance

Upvotes: 3

Views: 1711

Answers (2)

Ianhi
Ianhi

Reputation: 3152

If you don't mind them all being merged into one line than you should simply use plt.plot(x,y). However I think you would like to keep them as separate lines. For this you can specify the style arguments to your plot comamnd and then use the code from Stop matplotlib repeating labels in legend to prevent multiple legend entries.

import matplotlib.pyplot as plt
import numpy as np
from collections import OrderedDict

x = [np.random.randint(0,9) for i in range(10)]
y = [np.random.randint(0,9) for i in range(10)]
data = []
for i in range(0,10,2):
     data.append((x[i], x[i+1]))
     data.append((y[i], y[i+1]))

#Plot all with same style and label.
plt.plot(*data,linestyle='-',color='blue',label='LABEL')

#Single Legend Label
handles, labels = plt.gca().get_legend_handles_labels()
by_label = OrderedDict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys())

#Show Plot
plt.show()

Giving you
enter image description here

Upvotes: 1

screenpaver
screenpaver

Reputation: 1130

How about this?

import numpy as np
d = np.asarray(data)
plt.plot(d[:,0],d[:,1])
plt.show()

Upvotes: 0

Related Questions