gpt4 book ai didi

python 3 : matplotlib plotting four lines with dictionary

转载 作者:太空宇宙 更新时间:2023-11-04 08:43:56 25 4
gpt4 key购买 nike

你好,有一本字典,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是三行标签。如何绘制它。我试过下面的代码,但是错了,你能告诉我怎么做吗?

sample for what I want

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

output figure

关于 python 3 : matplotlib plotting four lines with dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42466279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com