1

Hi there is a dictionary, m={'A':[1.5,3.6,5.7,6,7,8], 'B':[3.5,5,6,8,4,5], 'C':[2.8,3.5,4.5,5.6,7.0,9.0]}. I want to plot three lines with python matplotlib at one figure(like the following figure). The x-aix is the same:[1, 2, 3, 4, 5, 6]. and three y values is the key(A, B, C)'s values. and A, B, C is three lines labels. how to plot it. I have tried by the following code, but it is wrong, could you tell me how to do it.

sample for what I want

  for k, v in dict_s:
        plt(range(1, 4), v, '.-', label=k)

1 Answer 1

5

Iterating a dictionary yields keys only.

>>> dict_s = {
...     'A': [1.5, 3.6, 5.7, 6, 7, 8],
...     'B': [3.5, 5, 6, 8, 4, 5],
...     'C': [2.8, 3.5, 4.5, 5.6, 7.0, 9.0]
... }
>>> for x in dict_s:
...     print(x)
...
A
C
B

If you need to iterate (key, value) pairs, use dict.items():

>>> for x in dict_s.items():
...     print(x)
...
('A', [1.5, 3.6, 5.7, 6, 7, 8])
('C', [2.8, 3.5, 4.5, 5.6, 7.0, 9.0])
('B', [3.5, 5, 6, 8, 4, 5])

import matplotlib.pyplot as plt

dict_s = {
    'A': [1.5, 3.6, 5.7, 6, 7, 8],
    'B': [3.5, 5, 6, 8, 4, 5],
    'C': [2.8, 3.5, 4.5, 5.6, 7.0, 9.0]
}

for k, v in dict_s.items():
    plt.plot(range(1, len(v) + 1), v, '.-', label=k)
    # NOTE: changed `range(1, 4)` to mach actual values count
plt.legend()  # To draw legend
plt.show()

output figure

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

2 Comments

thanks for @falsetru your kind answer, it is helpful. But I want to plot the labels for each line, how to do it, thanks!
thanks for @falsetru . I accept it. You are kind guy.

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.