基础示例
基础设置
首先进行基础的全局设置,无论是绘制什么图形,这些代码都是必不可少的
import matplotlib.pyplot as plt
from cycler import cycler
import numpy as np
# 进行必要的全局设置,让matplotlilb支持中文
plt.rcParams.update(
{
"font.sans-serif": "SimSun",
"axes.unicode_minus": False,
}
)
绘图样式
增添一个绘图样式
myenv = {
"figure.figsize": (4.8, 3.6), # 定义图片的长宽
# figure.figsize和dpi相乘就是图片长宽的具体像素值
"savefig.dpi": 200, # savefig.dpi是保存图片时的分辨率参数
"figure.dpi": 150, # figure.dpi是临时显示图片时的分辨率参数
# plot或scatter的每个系列的marker不一样
"axes.prop_cycle": cycler(
marker=["o", "^", "s"],
color=plt.get_cmap("Set1")(np.arange(0, 9, 3)),
),
# 线粗和标记大小
"lines.linewidth": 1, # 默认值
"lines.markersize": 3, # 和上述分辨率配合较好
# 经验证明下述文字大小和上述分辨率配合较好
"legend.fontsize": 8,
"xtick.labelsize": 12,
"ytick.labelsize": 12,
"axes.labelsize": 12,
"mathtext.fontset": "stix", # 公式字体,此项不要修改
}
绘制基本图形
with plt.rc_context(myenv):
fig, axe = plt.subplots(1, 1)
# ========绘制========
x_array = [1, 3, 5, 7, 9]
y_array = (2, 7, 1, 4, 3)
y_array2 = [8, 6, 4, 2, 0]
axe.plot(x_array, y_array, label="图例1")
axe.plot(x_array, y_array2, label="图例2")
# 详细说明:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html
axe.legend()
axe.set_ylabel("数量")
axe.set(xlabel="时间/h")
# ========整体布局========
# 防止xlabel或者ylabel超出保存或者显示范围
fig.tight_layout()
# 注意show或者save要写在with里面
plt.show()
# svg一般优于png,导出svg格式的图像时savefig.dpi将不起作用
fig.savefig("matplotlib绘图基础_1.svg")
绘制的图片如下
绘制复杂图形
下面的例子引入了多种详细设置,例如多子图、共x轴、设置刻度、设置标题、xlabel和ylabel使用latex语法等
with plt.rc_context(myenv):
fig, axes = plt.subplots(2, 1, figsize=(6.4, 7.2), sharex=True)
# ========绘制========
x_array = np.array([1, 3, 5, 7, 9])
y_array = np.array([0.11, 0.03, 0.05, 0.02, 0.07])
y_array2 = np.array([0.13, 0.10, 0.07, 0.08, 0.09])
axes[0].plot(x_array, y_array, label="图例1")
axes[0].plot(x_array, y_array2, label="图例2")
# 这里loc可以不填,系统会自动挑一个最好的位置
# 详细说明:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html
axes[0].legend(bbox_to_anchor=(1, 1), loc="upper left")
# 使用名称设置css4颜色
axes[1].bar(x_array, y_array2[::-1] * 100, color="goldenrod", label="图例3")
axes[1].legend()
# ========轴标签和轴刻度========
# axes[0].xaxis和axes[1].xaxis指向同一个xaxis
axes[0].xaxis.set_major_locator(plt.MultipleLocator(2))
axes[0].xaxis.set_minor_locator(plt.MultipleLocator(0.4))
axes[0].yaxis.set_major_locator(plt.MultipleLocator(0.03))
axes[0].yaxis.set_major_formatter("{:.1%}".format)
# 注意set_ylabel和set(xlabel=)作用相同
axes[0].set_ylabel("某某速率$\\frac{\\mathrm{d}^2\\varepsilon}{\\mathrm{d}x^2}$")
axes[0].set(ylim=(0, 0.16))
axes[1].set(xlabel="时间 $h$", xlim=(0.5, 9.5), ylim=(6, 18))
axes[1].yaxis.set_major_locator(plt.MultipleLocator(4))
# ========各类标题========
# 整张图片的总标题
fig.suptitle("总标题")
# plt.show的Windows窗口的标题
fig.canvas.manager.set_window_title("窗口标题")
# 每个子图自己的标题
axes[0].set_title("子图1标题")
# ========整体布局========
# 防止xlabel或者ylabel超出保存或者显示范围
fig.tight_layout()
# 子图共用x轴的视觉效果
fig.subplots_adjust(wspace=0, hspace=0)
# 注意show或者save要写在with里面
plt.show()
#svg一般优于png,导出svg格式的图像时savefig.dpi将不起作用
fig.savefig("matplotlib绘图基础_2.svg")
绘制的图片如下
折线图样式说明
用名称访问CSS4颜色和XKCD颜色
- https://matplotlib.org/stable/gallery/color/named_colors.html
- https://matplotlib.org/stable/users/explain/colors/colors.html
colormap
颜色系列分为两种,一种是由固定的N个颜色组成,使用方式为用形如plt.get_cmap(“Accent”)(np.arange(2,7))的方式获取该颜色系列指定序号的颜色,或用形如plt.get_cmap(“Accent”)(4)的方式获取一个颜色。
还有一种是渐变色,接收一个0~1之间的浮点数,使用方式为用形如plt.get_cmap(“Blues”)(np.linspace(0,1,n))的方式获取n种“等距”的颜色。
注意不能写成方括号!这是因为诸如plt.get_cmap(“Blues”)这样的函数返回的是一个类,加上圆括号表示构造对象。