Python子图函数参数
我在使用Python的subplot函数时遇到了困难,特别是在输入参数方面。
我想在同一张图片上绘制4个图表,具体要求如下:
left
space
right
space
left
space
right
我尝试了不同的三组数字,但输出的结果总是不对。
3 个回答
2
Matplotlib提供了几种方法来在一页上放置多个图表;我觉得最好的方法是gridspec,我记得它是在1.0版本中首次出现的。其他两种方法是(i)直接使用subplot进行索引和(ii)新的ImageGrid工具包。
GridSpec的工作方式类似于图形用户界面(GUI)工具包中的网格布局,用来在父框架中放置小部件。因此,从这个角度来看,它似乎是三种放置技术中最简单和最灵活的。
import numpy as NP
import matplotlib.pyplot as PLT
import matplotlib.gridspec as gridspec
import matplotlib.cm as CM
V = 10 * NP.random.rand(10, 10) # some data to plot
fig = PLT.figure(1, (5., 5.)) # create the top-level container
gs = gridspec.GridSpec(4, 4) # create a GridSpec object
# for the arguments to subplot that are identical across all four subplots,
# to avoid keying them in four times, put them in a dict
# and let subplot unpack them
kx = dict(frameon = False, xticks = [], yticks = [])
ax1 = PLT.subplot(gs[0, 0], **kx)
ax3 = PLT.subplot(gs[2, 0], **kx)
ax2 = PLT.subplot(gs[1, 1], **kx)
ax4 = PLT.subplot(gs[3, 1], **kx)
for itm in [ax1, ax2, ax3, ax4] :
itm.imshow(V, cmap=CM.jet, interpolation='nearest')
PLT.show()
除了将四个图表安排成“棋盘”配置(根据你的问题),我没有尝试调整这个配置,但这很简单。例如,
# to change the space between the cells that hold the plots:
gs1.update(left=.1, right=,1, wspace=.1, hspace=.1)
# to create a grid comprised of varying cell sizes:
gs = gridspec.GridSpec(4, 4, width_ratios=[1, 2], height_ratios=[4, 1])
3
好吧,关于sublot函数模板的文档不是很容易找到,内容如下:
subplot (number_of_graphs_horizontal, number of graphs_vertical, index)
让我们来看看上面Joe Kington的代码:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(4,2,1)
ax2 = fig.add_subplot(4,2,4)
ax3 = fig.add_subplot(4,2,5)
ax4 = fig.add_subplot(4,2,8)
fig.subplots_adjust(hspace=1)
plt.show()
你告诉matplotlib你想要一个4行2列的图表网格。ax1、ax2等等就是你在索引位置添加的图表,这个位置可以通过第三个参数来读取。你是从左到右、按行来计算的。
希望这能帮到你 :)
8
你是说像这样吗?
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(4,2,1)
ax2 = fig.add_subplot(4,2,4)
ax3 = fig.add_subplot(4,2,5)
ax4 = fig.add_subplot(4,2,8)
fig.subplots_adjust(hspace=1)
plt.show()