自动化子图的人口

时间:2014-07-18 15:32:12

标签: python matplotlib automation subplot

我正在编写一个python脚本,它将(1)获取每个子图的y值列表,以针对一组共同的x值进行绘图,(2)使每个子图分散 - 绘制并将其放在子图网格中的适当位置,以及(3)针对不同大小的子图网格完成这些任务。第三个陈述的意思是这样的:测试用例我在64个图,8行和8列的数组中使用结果。我希望代码能够处理各种网格尺寸的任何大小的数组(大致在50到80之间),而不必每次运行代码时都要回去并说#34;好的,这里&#39 ; s我需要的行数和列数。"

现在,我使用exec命令获取y值,并且工作正常。我能够制作每个子图并让它填充网格,但只有当我手动输入所有东西时(64次做同样的事情才是愚蠢的,所以我知道那里有了成为一种自动化的方法)。

有人可以建议一种可以实现这一目标的方法吗?我无法提供数据或我的代码,因为这是研究材料,不是我的发布。如果这个问题非常基础,或者我应该能够从现有文档中确定,请原谅。我是编程新手,可以使用一点指导!

2 个答案:

答案 0 :(得分:4)

对于这样的事情,一个有用的函数是plt.subplots(nrows, ncols),它将在常规网格上返回一个子图的数组(一个numpy对象数组)。

举个例子:

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(nrows=4, ncols=4, sharex=True, sharey=True)

# "axes" is a 2D array of axes objects.  You can index it as axes[i,j] 
# or iterate over all items with axes.flat

# Plot on all axes
for ax in axes.flat:
    x, y = 10 * np.random.random((2, 20))
    colors = np.random.random((20, 3))
    ax.scatter(x, y, s=80, facecolors=colors, edgecolors='')
    ax.set(xticks=np.linspace(0, 10, 6), yticks=np.linspace(0, 10, 6))

# Operate on just the top row of axes:
for ax, label in zip(axes[0, :], ['A', 'B', 'C', 'D']):
    ax.set_title(label, size=20)

# Operate on just the first column of axes:
for ax, label in zip(axes[:, 0], ['E', 'F', 'G', 'H']):
    ax.set_ylabel(label, size=20)

plt.show()

enter image description here

答案 1 :(得分:0)

如果您打算使用Python,您需要在Python Tutorial中漫步,了解您可以使用的语言和数据结构,网上有很好的教学材料,您可能需要考虑一些使用Python的计算机科学101 课程 - MIT OCW,edX,How To Think Like A Computer Scientist ......

在不知道完整细节的情况下,我想它可能是这样的,它是真正的代码和伪代码的混合:

yvalues = list()
while yvalues_exist:
    yvalues.append(get_yvalue)

#limit plot to eight columns
columns = 8
quotient, remainder = divmod(len(yvalues), columns)
rows = quotient
if remainder:
    rows = rows + 1
for n, yvalue in enumerate(yvalues):
    plt.subplot(rows, columns, n)
    plt.plot(yvalue)

list(),append(),while,divmod(),len(),if,for,enumerate()是所有Python语句,方法或内置函数。