Skip to main content
 首页 » 编程设计

python 3 : matplotlib plotting four lines with dictionary

2025年05月04日25mayingbao

你好,有一本字典,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]}。我想用 python matplotlib 在一个图中绘制三行(如下图)。 x-aix 相同:[1, 2, 3, 4, 5, 6]。三个 y 值是键(A、B、C)的值。 A、B、C是三行标签。如何绘制它。我试过下面的代码,但是错了,你能告诉我怎么做吗?

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

请您参考如下方法:

迭代字典只产生键。

>>> 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 

如果需要迭代(键,值)对,使用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()