本文将介绍如何使用 Python 的 matplotlib
库画图,记录一些常用的画图 demo 代码
安装
# 建议先切换到虚拟环境中
pip install matplotlib
中文显示
新版的 matplotlib
已经支持字体回退功能,因此可以直接设置字体为 Times New Roman
和 SimSun
(宋体)。这样英文会以 Times New Roman
显示,中文会以 宋体 显示
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = ['Times New Roman','SimSun']
折线图、点线图
plot
即可以绘制折线图,也可以绘制点线图,通过 marker
参数设置点的样式,markersize
设置点的大小
import matplotlib.pyplot as plt
# 设置中文字体为 Times New Roman 和 宋体
plt.rcParams['font.family'] = ['Times New Roman','SimSun']
# 生成数据
x = range(0, 6)
y = [i**3 for i in x]
# 绘制点线图
plt.plot(x, y, marker='o', markersize=6, label='y=x^3')
# 添加坐标轴标签
plt.xlabel('x')
plt.ylabel('y')
# 配置坐标轴范