2

Now I'm plotting using list like this:

eje_x1 = (0,6,10)
eje_y1 = (1,1,0)
label1 = 'Label1'
eje_x2 = (8,12,15,19)
eje_y2 = (0,1,1,0)
label2 = 'Label2'

eje_x = (eje_x1, eje_x2)
eje_y = (eje_y1, eje_y2)
labels = (label1, label2)

for x,y,label in zip(eje_x, eje_y, labels):
    plt.plot(x, y, label=label)
plt.legend(loc='best')
plt.show()

enter image description here

But I want to use a dictionary to clean my code, as the one below.

myDict = {
    'Label1': ((0,1),(6,1),(10,0)),
    'Label2': ((8,0),(12,1),(15,1),(19,0))
}

Can I plot this dict "directly"? I read some posts that one of the axes is the key, but not with this structure.

Thank you very much!

1 Answer 1

2

Iterating over the dictionary and rearranging the points in there:

for label, points in myDict.items():
    plt.plot(*zip(*points), label=label)

plt.legend(loc="best")
plt.show()

where zip(*...) kind of transposes the points so that xs are together and ys are together. The other * unpacks these to plt.plot to use as first & second argument that happens to be xs and ys,

to get

enter image description here


on zip(*...):

>>> points
((8, 0), (12, 1), (15, 1), (19, 0))

>>> list(zip(*points))
[(8, 12, 15, 19), (0, 1, 1, 0)]
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.