Skip to content

Matplotlib pyplot API

Matplotlib.pyplot 提供类 MATLAB 的绘图接口,可生成多种静态图表。

1 class · 8 methods

pyplot (plt)

8 methods

折线、散点、柱状、直方等常见图表的绘制与保存 API。

plt.plot(x, y, fmt)

绘制折线图,fmt 控制颜色与线型。

Parameters

NameTypeDescription
xarray_likex 轴数据
yarray_likey 轴数据
fmtstr格式串,如 'r-o'

Returns

list[Line2D] — 绘制的线条对象

Example

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)
plt.plot(x, np.sin(x), "r-", label="sin")
plt.legend()
plt.show()
plt.scatter(x, y)

绘制散点图。

Parameters

NameTypeDescription
xarray_likex 轴数据
yarray_likey 轴数据

Returns

PathCollection — 散点对象

Example

matplotlib
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
plt.scatter(x, y, c="blue")
plt.show()
plt.bar(x, height)

绘制柱状图。

Parameters

NameTypeDescription
xarray_like柱子的 x 位置/标签
heightarray_like柱子高度

Returns

BarContainer — 柱状对象

Example

matplotlib
import matplotlib.pyplot as plt

labels = ["A", "B", "C"]
values = [3, 7, 5]
plt.bar(labels, values, color="green")
plt.show()
plt.hist(x, bins)

绘制直方图,统计数据分布。

Parameters

NameTypeDescription
xarray_like输入数据
binsint | sequence分箱数或分箱边界

Returns

tuple — (counts, bins, patches)

Example

matplotlib
import matplotlib.pyplot as plt
import numpy as np

data = np.random.randn(1000)
plt.hist(data, bins=30, color="purple", alpha=0.7)
plt.show()
plt.xlabel(s) / plt.ylabel(s)

设置 x 轴或 y 轴的标签文本。

Parameters

NameTypeDescription
labelstr轴标签文本

Returns

Text — 标签文本对象

Example

matplotlib
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9])
plt.xlabel("时间 (s)")
plt.ylabel("幅值")
plt.show()
plt.title(s)

设置当前坐标轴的标题。

Parameters

NameTypeDescription
labelstr标题文本

Returns

Text — 标题文本对象

Example

matplotlib
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [1, 4, 9])
plt.title("平方曲线")
plt.show()
plt.legend()

为已声明 label 的图形元素添加图例。

Returns

Legend — 图例对象

Example

matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 50)
plt.plot(x, x, label="linear")
plt.plot(x, x ** 2, label="quadratic")
plt.legend(loc="upper left")
plt.show()
plt.show() / plt.savefig(fname)

show 弹窗显示图形,savefig 将图形保存到文件。

Parameters

NameTypeDescription
filenamestr保存的文件路径

Returns

None — 显示或保存图形

Example

matplotlib
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [3, 2, 1])
plt.savefig("plot.png", dpi=150)
# plt.show()  # 弹窗显示