在包含列表的字典上迭代以创建n个子批

2024-04-19 00:39:12 发布

您现在位置:Python中文网/ 问答频道 /正文

Type of chart that I want 所以我有一本字典,上面有几个列表:

{'A' : [1,2,4,6,7,8,10],
'B' : [1,2,4,6,4,3,7],
'C' : [3,2,1,6,2,3,4]}

同时,这些字典是由一个函数生成的,它们有不同的大小,但它们从不超过。。。6,7?在

我需要找到一种方法来绘制(matplotlib)与字典中条目数一样多的堆积图,把字典中的值作为y轴,把它们的索引作为x轴。我知道我永远不会将它们插入循环,但我不知道在matplotlib中最好的方法是什么,因为我对它不太熟悉。在


Tags: of方法函数列表字典thatmatplotlibtype
1条回答
网友
1楼 · 发布于 2024-04-19 00:39:12

可能是一种不用循环的方法,但是这里有一种方法可以用循环来实现。除非您有一大堆这样的字典,否则应该可以正常工作:

import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt

data = {'A' : [1,2,4,6,7,8,10],'B' : [1,2,4,6,4,3,7], 'C' : [3,2,1,6,2,3,4]}
fig, ax = sns.plt.subplots(len(data), 1, figsize=(7,5))
for a,key in zip(ax,data.keys() ):
    y = data[key]
    n = len(y)
    x = np.linspace(1,n,n)
    a.plot(x,y)
    # add labels/titles and such here

plt.show()

给出以下内容:enter image description here

如果你没有Seaborn,换掉

^{pr2}$

使用简单的matplotlib

fig, ax = plt.subplots(len(data), 1, figsize=(7,5))

相关问题 更多 >