matplotlib绘图细节-刻度、图例

导入依赖库:

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$')]
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值