[英]Reshape axes in figure using matplotlib
I am using a method from a library that used matplotlib to generate figures.我正在使用使用 matplotlib 生成图形的库中的方法。
I receive an array of axes:我收到一组轴:
[<matplotlib.axes._axes.Axes at 0x117a32a90>,
<matplotlib.axes._axes.Axes at 0x117bb1d68>,
<matplotlib.axes._axes.Axes at 0x10bae8390>,
<matplotlib.axes._axes.Axes at 0x10bb0add8>,
<matplotlib.axes._axes.Axes at 0x10c153898>,
<matplotlib.axes._axes.Axes at 0x1159412e8>,
<matplotlib.axes._axes.Axes at 0x115964d30>]
In the original figure, all axes are in the same row (see first figure and imagine having additional two axes on the right side).在原始图中,所有轴都在同一行中(请参见第一个图并想象右侧有额外的两个轴)。 I would like to reshape (à la numpy) the figure in order to create a grid of axes (see second figure).我想重塑(à la numpy)图形以创建一个轴网格(参见第二个图形)。
Is it possible?是否可以?
Following this answer , I tried to use GridSpec:按照这个答案,我尝试使用 GridSpec:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure()
axs = #get list of axes
gs = gridspec.GridSpec(3,3)
for i in range(3):
for j in range(3):
k = i+j*3
if k < len(axs):
axs[k].set_position(gs[k].get_position(fig))
fig.add_subplot(gs[k])
But it does not work, and I have not a complete grasp of GridSpec yet.但它不起作用,我还没有完全掌握GridSpec。 The figure displays the right number of subplots, but the axes are not added.该图显示了正确数量的子图,但未添加轴。
I think you are almost there.我想你快到了。 Without knowing what your plotting function is, I just made a dummy one for illustration.不知道你的绘图功能是什么,我只是做了一个虚拟的来说明。
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
def dummy_plots():
"""
Return a 1d array of dummy plots.
"""
_, ax_arr = plt.subplots(1, 9)
for ax in ax_arr.flat:
ax.plot([0, 1], [0, 1])
return ax_arr
axs = dummy_plots()
fig = plt.gcf()
gs = gridspec.GridSpec(3,3)
for i in range(3):
for j in range(3):
k = i+j*3
if k < len(axs):
axs[k].set_position(gs[k].get_position(fig))
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.