使用matplotlib python

时间:2018-09-04 17:05:07

标签: python matplotlib

目标是生成带有多个子图的单个图形。 以下代码生成4个单独的图

要绘制的子列表:可以在两组数据上使用相同的循环吗? x与y以及b与p的对比 这两个数据集之间的差异是x与y的关系为4,而b与p的关系为2

x = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y = [[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]

p = [[17, 16, 6, 15, 6, 7, 6, 7, 9, 11], [16, 13, 9, 11, 12, 13, 6, 12, 13, 7]]
b = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]]

colours=['r','g','b','k'] 

绘制它们的循环

for i in range(len(x)):
    plt.plot(x[i], y[i],colours[i])
    plt.show()

是否可以创建一个循环遍历每个已创建图的功能,并将其添加到一个图形或单个pdf中,以便可以一次查看所有四个图?

1 个答案:

答案 0 :(得分:0)

以下是使用subplots解决您的问题的方法:

from matplotlib import pyplot as plt

x = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y = [[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
colours=['r','g','b','k']

fig, axes = plt.subplots(nrows=2, ncols=2)
i = 0 # moving index to plot different sublists of data 
for r in axes:
    for c in r:
        c.plot(x[i], y[i], color=colours[i], label='Sublist %d'%(i+1))
        i += 1
        c.legend()

plt.show()

@SpghttCd建议的替代方法

for i, ax in enumerate(axes.flatten()):
    ax.plot(x[i], y[i], color=colours[i], label='Sublist %d'%(i+1))
    ax.legend()

输出

enter image description here

数据集2 (如以下评论中所述:

x = [[17, 16, 6, 15, 6], [7, 6, 7, 9, 11], [16, 13, 9, 11, 12], [13, 6, 12, 13, 7]] 
y = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]

输出(数据集2)

enter image description here