• matplotlib 文字标注(text、annotate)例程


    1、效果

    在这里插入图片描述

    2、代码

    import matplotlib.pyplot as plt
    import numpy as np
     
    x = np.linspace(-1,1,50)
    y1 = 2*x + 1
     
     plt.xlim((-1, 1))   # 设 x 轴最大最小值
    plt.ylim((-2, 5))   # 设 y 轴最大最小值
    plt.xlabel('I am x label', fontdict={'size': 14, 'color': 'red'})
    plt.ylabel('I am y label', fontsize=16)
    newTicks = np.linspace(-1, 1, 11)
    plt.xticks(newTicks)
    plt.tick_params(labelsize=13)   # 刻度字体大小13
    # y轴字体差别,设置成斜体
    plt.yticks([-2, -1.0, 0, 1.5, 3],
               [r'$really\ bad$', r'$little\ bad$', r'$normal$', r'$little\ good$', r'$pretty\ good$'])
    plt.plot(x, y1)
    
    # 获得当前的axis,继续画图
    ax = plt.gca()
    # 设置图像的上边、右边axis为无色
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    
    # 设置x轴坐标在下部
    ax.xaxis.set_ticks_position('bottom')
    # 设置x轴位于图像y=0处
    ax.spines['bottom'].set_position(('data', 0))
    # 设置x轴坐标在左部
    ax.yaxis.set_ticks_position('left')
    # 设置y轴位于图像x=0处
    ax.spines['left'].set_position(('data', 0))
    
    x0 = 0.5
    y0 = x0 * 2 + 1
    plt.scatter(x0, y0, s=50, color='green')
    plt.plot([x0, x0], [y0, 0], '--', color='black')
    plt.annotate('2x+1=y', xy=(x0, y0), xycoords='data', xytext=(+30, -30), textcoords='offset points',
                 fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.2'))
    plt.text(0.5, -1, 'This is a text', fontdict={'size': 12, 'color': 'green'})
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    3、说明

    3-1、plt.annotate(s, xy, *args, **kwargs)

    参数有:
    1)s:要标注的内容,字符串
    2)xy:要被标注的坐标,通过 xycoords 设置偏移方式
    3)xytext:标注文字的坐标,通过 textcoords 设置偏移方式
    4)xycoords:设置 xy 的偏移方式
    在这里插入图片描述

    5)textcoords:用于设置 xytext 的偏移方式
    在这里插入图片描述

    6)color:设置字体颜色
    {‘b’, ‘g’, ‘r’, ‘c’, ‘m’, ‘y’, ‘k’, ‘w’},
    或者 ‘black’, 'red’ 等
    或者 RGB/RGBA, 如: (0.1, 0.2, 0.5)、(0.1, 0.2, 0.5, 0.3)等

    7)arrowprops:箭头参数,类型为字典dict,其中的子参数有:
    width:箭头的宽度,以点为单位
    headwidth:箭头底部的宽度,以点为单位
    headlength:箭头的长度,以点为单位
    shrink:从两端“收缩”的分数
    facecolor:箭头颜色
    arrowstyle:箭头的样式
    connectionstyle:用于设置连接方式,可以设置弧度等
    可以用字符串代表一个箭头的样式,用于arrowstyle。

    4、参考资料

    1、matplotlib的使用——annotate标注的使用

  • 相关阅读:
    如何利用Api接口获取手机当前的网络位置信息
    android关于性能优化
    从校园到职场 | YK菌的2022年中总结
    javaScript 内存管理
    Mybatis-Puls MySQL存入json格式数据
    数据结构--哈希表(Hash Table)
    振动在线监测系统
    使用Passay库为Spring Boot Thymeleaf Web应用自定义密码策略验证
    2024年HarmonyOS鸿蒙最全恶补这份“阿里面试宝典”,秀出天际!_阿里巴巴面试宝典(1),2024年最新金三银四HarmonyOS鸿蒙面试的一些感受
    乘法逆元学习记录
  • 原文地址:https://blog.csdn.net/domodo2012/article/details/127597186