首页 > 解决方案 > 使用 matplib python 更改图形的位置和大小

问题描述

如何将每个图形分开一定距离,并分别增加图形的大小。如下图示例所示,您可以看到标题名称彼此非常接近,我想修改图表,使它们彼此相距足够远。我还想增加每个图的大小并给它们不同的方向。


fig = plt.figure(constrained_layout=True)
gs = fig.add_gridspec(6, 3)

#Plotting the compounding amount 
a1 = fig.add_subplot(gs[0:3, 0]) #subplot (row, column)
a1.set_title('Compounding Amount')
a1.plot(bar_positions_x_list,Amount_list)

#plotting the non compounding amount
c1 = fig.add_subplot(gs[3:6,0])
c1.set_title('Non-Compounding Amount')
c1.plot(bar_positions_x_list, Non_compounding_list)

#plotting the short compounding amount 
a2 = fig.add_subplot(gs[0:3, 1])
a2.set_title('Short Compounding')
a2.plot(x_short, S_Amount_list)

#plotting the long compounding amount
a3 = fig.add_subplot(gs[3:6, 1])
a3.set_title('Long Compounding')
a3.plot(x_long,L_Amount_list)


c2 = fig.add_subplot(gs[2:4, 2])
c2.set_title('Short Non-Compounding')
c2.plot(x_short,S_Non_compounding_list)

c3 = fig.add_subplot(gs[4:6, 2])
c3.set_title('Long Non-Compounding')
c3.plot(x_long,L_Non_compounding_list)

plt.show()

图表:

在此处输入图像描述

标签: pythonpython-3.xdataframematplotlib

解决方案


您可以通过提供figsizeplt.figure具有两个值(图形的宽度和高度,以英寸为单位)的参数来增加整个图形的大小(从而也增加各个子图的大小)。默认情况下,此设置为[6.4, 4.8]。例如,将宽度和高度加倍:

fig = plt.figure(figsize=[12.8, 9.6], constrained_layout=True)

由于更改 时不会增加字体大小figsize,因此这很可能会使您的子图标题相距足够远。但是,如果您想进一步增加距离,可以使用构造函数wspaceandhspace参数GridSpec来配置子图之间的间距。0这两个值都是和之间的浮点数1,并且是“为子图之间的空间保留的宽度/高度量,表示为平均轴宽度/高度的一部分”(从文档中引用)。您很可能必须调整这些值以获得所需的结果,但您可以按如下方式使用它们:

gs = fig.add_gridspec(6, 3, wspace=0.1, hspace=0.1)

但是,该constrained_layout设置会导致 matplotlib 忽略wspacehspace值,因此您必须将其设置为False.


推荐阅读