繁体   English   中英

使用Matplotlib Python将单个图绘制成一个图

[英]Individual plots into one figure using matplotlib python

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

要绘制的子列表:可以在两组数据上使用相同的循环吗? x vs. y和b vs. p这两个数据集之间的差异是x vs. y将绘制4个图,而b vs. 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的函数,以便可以一次查看所有四个图?

这是使用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()

输出量

在此处输入图片说明

数据集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)

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM