您的位置:

如何在 Matplotlib 中更改绘图大小

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

用户应该在创建图时优化图的大小。在本教程中,我们将讨论根据用户所需尺寸更改默认绘图大小或调整给定绘图大小的各种方法。

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

用户可以使用 set_figheight() 更改高度,使用 set_figwidth() 更改地块宽度。

示例:


# first, import the matplotlib library
import matplotlib.pyplot as plot

# The values on x-axis
x_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# The values on y-axis
y_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# Now, name the x and y axis
plot.xlabel('X - AXIS')
plot.ylabel('Y - AXIS')

#Then, plot the line plot with its default size
print ("The plot is plotted in its default size: ")
plot.plot(x_axis, y_axis)
plot.show()

# Now, plot the line plot after changing the size of its width and height
K = plot.figure()
K.set_figwidth(5)
K.set_figheight(2)

print ("The plot is plotted after changing its size: ")
plot.plot(x_axis, y_axis)
plot.show()

输出:

The plot is plotted in its default size: 

The plot is plotted after changing its size: 

方法 2:使用 figsize()函数

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

语法:


Plot.figure(figsize = (x_axis, y_axis)

其中 x 轴为宽度, y 轴为高度,单位为英寸。

示例:


# First, import the matplotlib library
import matplotlib.pyplot as plot

# The values on x-axis
x_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# The values on y-axis
y_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

#Then, plot the line plot with its default size
print ("The plot is plotted in its default size: ")
plot.plot(x_axis, y_axis)
plot.show()

# Now, plot the line plot after changing the size of figure to 3 X 3
plot.figure(figsize = (3, 3))
print ("The plot is plotted after changing its size: ")
plot.plot(x_axis, y_axis)
plot.show()

输出:

The plot is plotted in its default size: 

The plot is plotted after changing its size: 

方法 3:通过改变默认的参数

用户可以根据自己的需要,通过设置图形、图形尺寸、来永久改变图形的默认尺寸

示例:


# First, import the matplotlib library
import matplotlib.pyplot as plot

# The values on x-axis
x_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# The values on y-axis
y_axis = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# now, name the x axis
plot.xlabel('X - AXIS')
# name the y axis
plot.ylabel('Y - AXIS')

#Then, plot the line plot with its default size
print ("The plot is plotted in its default size: ")
plot.plot(x_axis, y_axis)
plot.show()

# Now, change the rc parameters and plot the line plot after changing the size.
plot.rcParams['figure.figsize'] = [3, 3]

print ("The plot is plotted after changing its size: ")
plot.plot(x_axis, y_axis)
plot.show()

plot.scatter(x_axis, y_axis)
plot.show()

输出:

The plot is plotted in its default size: 

The plot is plotted after changing its size: