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

2024-04-23 15:27:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个由几个共享x/y轴的子块组成的绘图。 从文档来看应该是这样的(尽管我的子块是分散的):(code here)

3 subplots sharing x and y axis

但我想动态创建子块!

所以子块的数量取决于前一个函数的输出。(根据脚本的输入,每个图可能有3到15个子块,每个子块来自不同的数据集。)

有人能告诉我怎么做到吗?


Tags: 数据函数文档脚本绘图数量herecode
3条回答

Based on this post,你想做的是这样的事情:

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() 

但是,Paul Hanswer指向名为gridspec的子模块,这可能使上述操作更简单。我把它留给读者作为练习。

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值不同,则需要为每个绘图指定它们。

subplot的工作方式如下,例如,如果我的子块值为3,1,1。这将创建一个3x1栅格并将打印放置在第一个位置。在下一个迭代中,如果我的subplot值是3,1,2,它将再次创建一个3x1网格,但将绘图放置在第二个位置,以此类推。

假设您知道要使用的子批次总数和列总数:

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)

第一个实例只占完全由子块填充的行,然后在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()

请注意,您需要范围位置将子批次移动到正确的位置。

相关问题 更多 >