Reputation: 1694
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.
for k, v in dict_s:
plt(range(1, 4), v, '.-', label=k)
Upvotes: 1
Views: 4323
Reputation: 369054
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()
Upvotes: 5