在 matplotlib 中动态添加/创建子图 [英] Dynamically add/create subplots in matplotlib

查看:45
本文介绍了在 matplotlib 中动态添加/创建子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个由几个共享 x/y 轴的子图组成的图.它应该从文档中看起来像这样(尽管我的子图将是散点图):(代码在这里)

I want to create a plot consisting of several subplots with shared x/y axes. It should look something like this from the documentation (though my subplots will be scatterblots): (code here)

但我想动态创建子图!

所以子图的数量取决于前一个函数的输出.(每个图表可能有大约 3 到 15 个子图,每个都来自不同的数据集,具体取决于我的脚本输入.)

So the number of subplots depends on the output of a previous function. (It will probably be around 3 to 15 subplots per diagram, each from a distinct dataset, depending on the input of my script.)

谁能告诉我如何做到这一点?

Can anyone tell me how to accomplish that?

推荐答案

import matplotlib.pyplot as plt
from pylab import *
import numpy as np

x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

subplots_adjust(hspace=0.000)
number_of_subplots=3

for i,v in enumerate(xrange(number_of_subplots)):
    v = v+1
    ax1 = subplot(number_of_subplots,1,v)
    ax1.plot(x,y)

plt.show()

此代码有效,但您需要更正轴.我过去常常 subplot 在同一列中绘制 3 个图形.您需要做的就是为 number_of_plots 变量分配一个整数.如果每个图的 X 和 Y 值不同,您需要为每个图分配它们.

This code works but you will need to correct the axes. I used to subplot to plot 3 graphs all in the same column. All you need to do is assign an integer to number_of_plots variable. If the X and Y values are different for each plot you will need to assign them for each plot.

subplot 的工作原理如下,例如,如果我有一个 3,1,1 的子图值.这将创建一个 3x1 网格并将绘图放置在第一个位置.在下一次交互中,如果我的 subplot 值为 3,1,2,它会再次创建一个 3x1 网格,但将绘图放在第二个位置,依此类推.

subplot works as follows, if for example I had a subplot values of 3,1,1. This creates a 3x1 grid and places the plot in the 1st position. In the next interation if my subplot values were 3,1,2 it again creates a 3x1 grid but places the plot in the 2nd position and so forth.

这篇关于在 matplotlib 中动态添加/创建子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆