在matplotlib中动态添加/创建子图

Cod*_*Cat 34 python matplotlib

我想创建一个由多个具有共享x/y轴的子图组成的图.它应该从文档中看起来像这样(虽然我的子图将是scatterblots):( 这里的代码)

3个子图共享x和y轴

但我想动态创建子图!

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

谁能告诉我如何实现这一目标?

Har*_*pal 24

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()
Run Code Online (Sandbox Code Playgroud)

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

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

  • 为什么不只是整理代码而不是捍卫它.`for in in range(3):...` (3认同)
  • @Harpal,如何为整个情节的每个子情节和图例添加标题? (2认同)

Sar*_*ica 17

根据这篇文章,你想要做的是这样的:

import matplotlib.pyplot as plt

# Start with one
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3])

# Now later you get a new subplot; change the geometry of the existing
n = len(fig.axes)
for i in range(n):
    fig.axes[i].change_geometry(n+1, 1, i+1)

# Add the new
ax = fig.add_subplot(n+1, 1, n+1)
ax.plot([4,5,6])

plt.show() 
Run Code Online (Sandbox Code Playgroud)

然而,Paul H回答指向了一个名为gridspec的子模块,它可能使上述更容易.我将这作为练习留给读者^ _~.

  • http://stackoverflow.com/questions/31575399/dynamically-add-subplots-in-matplotlib-with-more-than-one-column (2认同)

Mat*_*oni 15

假设您知道要使用的总子图总列数:

import matlab.pyplot as plt

# Subplots are organized in a Rows x Cols Grid
# Tot and Cols are known

Tot = number_of_subplots
Cols = number_of_columns

# Compute Rows required

Rows = Tot // Cols 
Rows += Tot % Cols

# Create a Position index

Position = range(1,Tot + 1)
Run Code Online (Sandbox Code Playgroud)

行的第一个实例仅考虑完全由子图填充的行,然后再添加一个行,如果1或2或者...... Cols - 1个子图仍然需要位置.

然后创建图形并添加带有for循环的图.

# Create main figure

fig = plt.figure(1)
for k in range(Tot):

  # add every single subplot to the figure with a for loop

  ax = fig.add_subplot(Rows,Cols,Position[k])
  ax.plot(x,y)      # Or whatever you want in the subplot

plt.show()
Run Code Online (Sandbox Code Playgroud)

请注意,您需要范围位置才能将子图移动到正确的位置.