猿问

在循环中绘制子图

z = {'A': [0.3618426, 0.36146951], 'B': [1.8908799, 1.904695], 'C': [2.1813462e+08, 2.1833622e+08], 'D': [0.89925492, 0.89953589], 'E': [2.6356747, 2.6317911], 'F': [2.2250445e+08, 2.2501808e+08], 'G': [2.0806053e+08, 2.0691238e+08], 'H': [0.37242803, 0.37611806]}

k = [1,2]


for key in z:

plt.subplot(4,4,1)

plt.plot(k,[z[key][0],z[key][1]], 'ro-')

plt.show()

我会尽量说清楚。z 是一个大小不同的字典。我想做的是绘制字典数量,比如 4 列,但行应该根据生成的图的数量而增加,例如,如果有 16 个要绘制的键,我应该以 4 行 4 列的数字结束。如何我可以这样做吗?


杨__羊羊
浏览 111回答 3
3回答

喵喵时光机

绘制多个图形的基本形式是下面的方法 作为先决条件,您只需要决定列数。cols=3 剩下的循环过程由词典的数量来完成。import matplotlib.pyplot as pltimport pandas as pdimport mathz = {'A': [0.3618426, 0.36146951], 'B': [1.8908799, 1.904695], 'C': [2.1813462e+08, 2.1833622e+08], 'D': [0.89925492, 0.89953589], 'E': [2.6356747, 2.6317911], 'F': [2.2250445e+08, 2.2501808e+08], 'G': [2.0806053e+08, 2.0691238e+08], 'H': [0.37242803, 0.37611806]}k = [1,2]cols = 3rows = math.ceil(len(z) / cols)fig, axes = plt.subplots(rows, cols, figsize=(16,12))dict_keys = [k for k in z.keys()]l = 0for i in range(rows):    for j in range(cols):        if len(z) == l:            break        else:            key = dict_keys[i+j]            axes[i][j].plot(k, [z[key][0],z[key][1]], 'ro-')        l += 1plt.show()

白猪掌柜的

如果没有重复的子图,@r-beginners 的答案是完美的。我做了两个小修改:import matplotlib.pyplot as pltimport mathz = {'A': [0.3618426, 0.36146951], 'B': [1.8908799, 1.904695], 'C': [2.1813462e+08, 2.1833622e+08], 'D': [0.89925492, 0.89953589],     'E': [2.6356747, 2.6317911], 'F': [2.2250445e+08, 2.2501808e+08], 'G': [2.0806053e+08, 2.0691238e+08], 'H': [0.37242803, 0.37611806]}k = [1, 2]cols = 3rows = math.ceil(len(z) / cols)fig, axes = plt.subplots(rows, cols, figsize=(16, 12))dict_keys = [m for m in z.keys()]l = 0for i in range(rows):    for j in range(cols):        if len(z) == l:            break        else:            key = dict_keys[l]      # modified            axes[i][j].plot(k, [z[key][0], z[key][1]], 'ro-')            l += 1          # modifiedplt.show()

郎朗坤

这是一个可能对您有帮助的代码:from math import ceil# 9 elements in my dict (4x4 + 1)z = {'A': [0.3618426, 0.36146951], 'B': [1.8908799, 1.904695], 'C': [2.1813462e+08, 2.1833622e+08], 'D': [0.89925492, 0.89953589], 'E': [2.6356747, 2.6317911], 'F': [2.2250445e+08, 2.2501808e+08], 'G': [2.0806053e+08, 2.0691238e+08], 'H': [0.37242803, 0.37611806], 'X': [0.37242803, 0.37611806]}k = [1,2]plt.subplots(figsize=(16,8)) # optional# fixed number of columnscols = 4# number of rows, based on colsrows = ceil(len(z) / cols)# iterate through indices and keysfor index, key in enumerate(z):    # new subplot with (i + 1)-th index laying on a grid    plt.subplot(rows, cols, index + 1)     # drawing the plot    plt.plot(k, [z[key][0], z[key][1]], 'ro-')# render everythingplt.show()
随时随地看视频慕课网APP

相关分类

Python
我要回答