Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 212
Quantifeye Avatar asked Mar 01 '26 20:03

Quantifeye


1 Answers

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

like image 184
Ianhi Avatar answered Mar 04 '26 09:03

Ianhi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!