📌  相关文章
📜  如何更改用 matplotlib 绘制的图形的大小?

📅  最后修改于: 2022-05-13 01:55:12.571000             🧑  作者: Mango

如何更改用 matplotlib 绘制的图形的大小?

matplotlib 的主要目的是创建一个表示数据的图形。可视化数据的用途是通过将数据整理成更易于理解的形式来讲述故事,突出趋势和异常值。我们可以用所有不同类型的数据填充图形,包括轴、图形、几何形状等。“当”我们绘制图形时,我们可能希望将图形的大小设置为特定大小。您可能希望使图形尺寸更宽、高度更高等。

这可以通过称为figsizematplotlib属性来实现。 figsize 属性允许我们以英寸为单位指定图形的宽度和高度。

figsize 属性是函数figure() 的一个参数。它是一个可选属性,默认情况下该图的尺寸为 (6.4, 4.8)。这是一个标准图,其中函数中未提及该属性。

通常每个单位英寸为 80 x 80 像素。每单位英寸的像素数可以通过参数dpi 改变,也可以在同一个函数中指定。

方法:

  • 我们创建一个变量 plt_1,并将其设置为等于 plt.figure(figsize=(6,3))。
  • 这将创建一个图形对象,其宽度为 6 英寸,高度为 3 英寸。
  • figsize 属性的值是 2 个值的元组。

示例 1

Python3
# We start by importing matplotlib
import matplotlib.pyplot as plt
 
# Plotting a figure of width 6 and height 3
plt_1 = plt.figure(figsize=(6, 3))
 
# Let's plot the equation y=2*x
x = [1, 2, 3, 4, 5]
 
# y = [2,4,6,8,10]
y = [x*2 for x in x]
 
# plt.plot() specifies the arguments for x-axis
# and y-axis to be plotted
plt.plot(x, y)
 
# To show this figure object, we use the line,
# fig.show()
plt.show()


Python3
# We start by importing matplotlib
import matplotlib.pyplot as plt
 
# Plotting a figure of width 3 and height 6
plt_1 = plt.figure(figsize=(3, 6))
 
# Let's plot the equation y=2*x
x = [1, 2, 3, 4, 5]
 
# y = [2,4,6,8,10]
y = [x*2 for x in x]
 
# plt.plot() specifies the arguments for
# x-axis and y-axis to be plotted
plt.plot(x, y)
 
# To show this figure object, we use the line,
# fig.show()
plt.show()


输出:

如果您使用的是 jupyter notebooks 以外的Python IDE,则此方法有效。如果您正在使用

jupyter 笔记本,那么你就不会使用 plt.show()。相反,您将在

在导入 matplotlib、%matplotlib 内联后立即编写代码。

示例 2:

为了在 matplotlib 中查看图形大小的动态特性,现在我们创建一个尺寸反转的图形。高度现在将是宽度的两倍。

蟒蛇3

# We start by importing matplotlib
import matplotlib.pyplot as plt
 
# Plotting a figure of width 3 and height 6
plt_1 = plt.figure(figsize=(3, 6))
 
# Let's plot the equation y=2*x
x = [1, 2, 3, 4, 5]
 
# y = [2,4,6,8,10]
y = [x*2 for x in x]
 
# plt.plot() specifies the arguments for
# x-axis and y-axis to be plotted
plt.plot(x, y)
 
# To show this figure object, we use the line,
# fig.show()
plt.show()

输出: