Skip to main content
 首页 » 编程设计

python之遍历包含列表的字典以创建 n 个子图

2024年10月17日7pengyingh

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_axis,并将它们的索引作为 x_axis。我知道我永远不会将它们插入循环中,但我不知道在 matplotlib 中执行此操作的最佳方法是什么,因为我并不精通它。

请您参考如下方法:

可能是一种无需循环的方法,但这里有一种使用循环的方法。除非你有大量这些词典,否则这应该可以正常工作:

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

给出以下内容:

如果你没有Seaborn,替换

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

使用普通的 matplotlib

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