如何在 Matplotlib 中更改绘图大小

2025年3月17日 | 阅读 3 分钟

在数据可视化中,图表是可视化表示数据的最有效方式。如果绘制得不够详细,它可能会显得复杂。Python 拥有 Matplotlib,它用于以绘图形式表示数据。

用户在创建图表时应优化图表的大小。在本教程中,我们将讨论改变默认图表大小以符合用户所需尺寸或调整现有图表大小的各种方法。

方法 1:使用 set_figheight() 和 set_figwidth()

用户可以使用 set_figheight() 更改高度,并使用 set_figwidth() 更改图表的宽度。

示例

输出

The plot is plotted in its default size: 
How to Change Plot Size in Matplotlib

The plot is plotted after changing its size: 
How to Change Plot Size in Matplotlib

方法 2:使用 figsize() 函数

figsize() 函数接受两个参数,即宽度和高度(以英寸为单位)。默认情况下,宽度 = 6.4 英寸,高度 = 4.8 英寸。

语法

其中 x_axis 是宽度,y_axis 是高度(以英寸为单位)。

示例

输出

The plot is plotted in its default size: 
How to Change Plot Size in Matplotlib

The plot is plotted after changing its size: 
How to Change Plot Size in Matplotlib

方法 3:通过更改默认 rcParams

用户可以通过设置 figure.figsize 来永久更改图形的默认大小以满足他们的需求。

示例

输出

The plot is plotted in its default size: 
How to Change Plot Size in Matplotlib

The plot is plotted after changing its size: 
How to Change Plot Size in Matplotlib
How to Change Plot Size in Matplotlib