导入依赖库:
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FormatStrFormatter
from matplotlib import ticker, cm
from matplotlib.pyplot import MultipleLocator
import matplotlib.ticker as mticker
常用指令
1. 调整坐标轴最大最小刻度:
# 设置主刻度
xmajorLocator = MultipleLocator(2)
ax.xaxis.set_major_locator(xmajorLocator)
# 设置副刻度
xminorLocator = MultipleLocator(1)
ax.xaxis.set_minor_locator(xminorLocator)
2.设置刻度线粗细、长短、朝内外等属性:
# 主刻度线特征
# top、right控制上、右侧是否有刻度
# direction控制朝内、外
ax.tick_params(which="major", top=True, right=True, direction='in', length=5, width=1.5)
# 副刻度线特征
ax.tick_params(which="minor", top=True, right=True, direction='in', length=3, width=1.0)
3.科学计数法:
①:无括号形式
formatter = ticker.ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
formatter.set_powerlimits((0,0))
ax[i, j].yaxis.set_major_formatter(formatter)
②:有括号形式
class CustomScalarFormatter(mticker.ScalarFormatter):
def __init__(self, useMathText=False, useOffset=True):
super().__init__(useMathText=useMathText, useOffset=useOffset)
def get_offset(self):
# 调用父类方法获取原始偏移量文本
offset = super().get_offset()
# 如果存在偏移量,则添加圆括号
if offset:
return f"({offset})"
return ""
# 有括号版
ax[i, j].yaxis.set_major_formatter(CustomScalarFormatter(useMathText=True))
ax[i, j].ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
4.刻度显示数值形式(显示小数位数)
# 设置主刻度
xmajorLocator = MultipleLocator(2) # 2的倍数
xmajorFormatter = FormatStrFormatter('%.2f') # 2位小数
ax[i][j].xaxis.set_major_locator(xmajorLocator)
# 设置副刻度
xminorLocator = MultipleLocator(1)
xminorFormatter = FormatStrFormatter('%.2f')
ax[i][j].xaxis.set_minor_locator(xminorLocator)
5.多子图中添加编号
# transform表示以相对子图的比例位置添加编号
ax[0, 0].text(x=-0.22, y=1.15, s=r'$(a1)$', fontsize=20, transform=ax[0, 0].transAxes)
# 按照子图刻度线对应位置绘图(绝对位置)
ax[0, 0].text(x=-0.22, y=1.15, s=r'$(a1)$', fontsize=20)
6.添加图例(legend)
plt.legend(handles=handles, labels=labels, fontsize=18, labelspacing=0.5, handletextpad=0.06,loc='upper center', edgecolor='black',
bbox_to_anchor=(0.52, 1.15), ncol=5, framealpha=1))
- handles:可见对象(如线条、形状)序列,与labels配合使用(存在对应关系);
- labels:类型为字符串列表,即图例中显示的文本集合;
- labelspacing:标签上下间距;
- columnspacing:标签列与标签列的间距;
- handletextpad:对象(线条、形状)与labels文本之间的间距;
- bbox_to_anchor:定位
- framealpha:线条透明度
- ncol:列数
7.创建图例(legend)
legend_elements = [Line2D([0], [0], linestyle='-', color='black', label=r'$A$'),
Line2D([0], [0], linestyle='--', color='black', label=r'$B$')]