• 如何使用Matplotlib模块的text()函数给柱形图添加美丽的标签数据?


    1 简单引入

    • 在进行数据分析时,当一些图表数据,比如柱形图我们想让它更直观的显示一些内容,有时候会给柱形图添加标签, 那如何实现这样的效果呢?
    • 还有比如我们把某手机品牌1-12月每月的销量制作成柱形图,那如何在柱形图上显示具体的每月销量的标签?
    • 带着这个问题,我们来研究下这个功能吧;
    • 本文使用的是PythonMatplotlib模块的text()函数,它能给图表的指定位置添加标签、注释或标注。

    2 关于text()函数

    2.1 Matplotlib安装

    • text()函数是PythonMatplotlib模块一个函数;
    • 具体引入的话,需要先安装Matplotlib模块:
    pip install matplotlib
    
    • 1

    在这里插入图片描述

    2.2 text()引入

    • 需要插入pylot模块:
    import matplotlib.pyplot as plt
    
    • 1
    • 使用方法是:
    plt.text()
    
    • 1

    2.3 text()源码

    • 路径如下:
    Python37\Lib\site-packages\matplotlib\pyplot.py
    
    • 1
    • 源码如下:
    # Autogenerated by boilerplate.py.  Do not edit as changes will be lost.
    @_copy_docstring_and_deprecators(Axes.text)
    def text(x, y, s, fontdict=None, **kwargs):
        return gca().text(x, y, s, fontdict=fontdict, **kwargs)
    
    • 1
    • 2
    • 3
    • 4

    2.4 text()参数说明

    • 详细参数说明如下:
    参数说明
    x, y:float放置文本的位置
    s: str文本
    Fontdict:默认无覆盖默认文本属性的字典
    **kwargs文本属性

    2.5 text()两个简单示例

    • 示例1:在一个没有任何数据的图表上显示一个标签:
    # -*- coding:utf-8 -*-
    # 作者:虫无涯
    # 日期:2023/11/17 
    # 文件名称:test_plt_text().py
    # 作用:Matplotlib模块的text()函数的应用
    # 联系:VX(NoamaNelson)
    # 博客:https://blog.csdn.net/NoamaNelson
    
    import matplotlib.pyplot as plt
    
    plt.figure(figsize=(5, 5))
    plt.text(0.5, 0.5, "这是一个标签")
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 结果显示如下,发现中文是乱码的:
      在这里插入图片描述
    • 要解决中文乱码,我们加一行代码:
    plt.rcParams['font.sans-serif'] = ['SimHei']
    
    • 1
    • 之后显示如下:
      在这里插入图片描述
    • 示例2:我们添加几个点数据,并设置文本数据:
    # -*- coding:utf-8 -*-
    # 作者:虫无涯
    # 日期:2023/11/17 
    # 文件名称:test_plt_text().py
    # 作用:Matplotlib模块的text()函数的应用
    # 联系:VX(NoamaNelson)
    # 博客:https://blog.csdn.net/NoamaNelson
    
    import matplotlib.pyplot as plt
    
    plt.figure(figsize=(5, 5))
    x = [1, 2, 6]
    x_pos = 1
    y_pos = 1.5
    
    plt.text(x_pos, y_pos, "这是一个标签")
    plt.plot(x)
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 结果显示如下:
      在这里插入图片描述

    3 柱形图绘制并添加标签

    3.1 目标数据

    • 我们先创建一个产品0-12月份的每月销量数据表plt_text.xlsx
    月份	    销量
    11200
    22400
    3112
    4125
    5555
    6135
    7136
    8269
    9627
    10876
    11350
    12233
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    3.2 读取excel数据

    class TestPltText():
        def __init__(self):
            super(TestPltText, self).__init__()
    
            # 读取excel数据
            self.data = "./plt_text.xlsx"
            self.data_excel = pd.DataFrame(pd.read_excel(self.data))
    
            # 获取相关内容
            self.data_content = self.data_excel[["月份", "销量"]]
            self.data_content01 = self.data_content.sort_values("销量", ascending=True)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    3.3 设置窗口大小和xy轴坐标

        def test_plt_text(self):
    
            # 设置窗口大小
            plt.figure(figsize=(5, 4))
    
            # 构造x,y轴坐标
            y = np.array(list(self.data_content01["销量"]))
            x_ticks = list(self.data_content01["月份"])
            x = range(len(x_ticks))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3.4 绘制柱形图

    # 绘制柱形图
    plt.bar(x, y, width=0.5, align="center", color="b", alpha=0.6)
    plt.xticks(range(len(x_ticks)), x_ticks, fontsize=6, rotation=90)
    
    • 1
    • 2
    • 3

    3.5 设置标签

    # x、y轴标签
    plt.xlabel('月份')
    plt.ylabel('销量')
    plt.title('月销量(万)')
    # 设置标签
    for label1, label2 in zip(x, y):
        plt.text(label1, label2+10,
                 '%.0f' % label2,
                 ha='center',
                 va='bottom',
                 fontsize=9)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    3.6 解决乱码和结果显示

    # 设置y轴的范围
    plt.ylim(0, 2600)
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.show()
    
    • 1
    • 2
    • 3
    • 4

    4 完整源码

    # -*- coding:utf-8 -*-
    # 作者:虫无涯
    # 日期:2023/11/17 
    # 文件名称:test_plt_text().py
    # 作用:Matplotlib模块的text()函数的应用
    # 联系:VX(NoamaNelson)
    # 博客:https://blog.csdn.net/NoamaNelson
    
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import random
    
    
    class TestPltText():
        def __init__(self):
            super(TestPltText, self).__init__()
    
            # 读取excel数据
            self.data = "./plt_text.xlsx"
            self.data_excel = pd.DataFrame(pd.read_excel(self.data))
    
            # 获取相关内容
            self.data_content = self.data_excel[["月份", "销量"]]
            self.data_content01 = self.data_content.sort_values("销量", ascending=True)
    
        def test_plt_text(self):
    
            # 设置窗口大小
            plt.figure(figsize=(5, 4))
    
            # 构造x,y轴坐标
            y = np.array(list(self.data_content01["销量"]))
            x_ticks = list(self.data_content01["月份"])
            x = range(len(x_ticks))
    
            # 绘制柱形图
            plt.bar(x, y, width=0.5, align="center", color="b", alpha=0.6)
            plt.xticks(range(len(x_ticks)), x_ticks, fontsize=6, rotation=90)
    
            # x、y轴标签
            plt.xlabel('月份')
            plt.ylabel('销量')
            plt.title('月销量(万)')
            # 设置标签
            for label1, label2 in zip(x, y):
                plt.text(label1, label2+10,
                         '%.0f' % label2,
                         ha='center',
                         va='bottom',
                         fontsize=9)
            # 设置y轴的范围
            plt.ylim(0, 2600)
            plt.rcParams['font.sans-serif'] = ['SimHei']
            plt.show()
    
    
    if __name__ == "__main__":
        plt_text = TestPltText()
        plt_text.test_plt_text()
    
    • 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
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    5 结果显示

    5.1 从小到大排序

    • 设置如下:
    self.data_content01 = self.data_content.sort_values("销量", ascending=True)
    
    • 1
    • 结果显示:
      在这里插入图片描述

    5.2 从大到小排序

    • 设置如下:
    self.data_content01 = self.data_content.sort_values("销量", ascending=True)
    plt.bar(x, y, width=0.5, align="center", color="c", alpha=0.6)
    
    • 1
    • 2
    • 结果显示:
      在这里插入图片描述

    5.3 原序列输出显示

    • 不进行排序,直接进行输出原图:
     # 构造x,y轴坐标
    y = np.array(list(self.data_content["销量"]))
    x_ticks = list(self.data_content["月份"])
    x = range(len(x_ticks))
    
    plt.bar(x, y, width=0.5, align="center", color="k", alpha=0.6)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 结果显示:
      在这里插入图片描述
  • 相关阅读:
    城市网吧视频智能监控方案,实现视频远程集中监控
    Mysql根据经纬度查询半径多少以内的数据,画个圈圈查数据库
    java - 设计模式 - 状态模式
    电脑录屏快捷键,轻松提升录屏效率
    HTTPS内容详解(图解HTTP协议)
    ImageNet classification with deep convolutional neural networks
    TDengine 成功“晋级” Percona Live 2023 银牌赞助商,开发者驻足关注
    力扣1038. 从二叉搜索树到更大和树(java,树的中序遍历解法)
    电脑密码忘了怎么解除?最简单操作的方法
    多路复用补充
  • 原文地址:https://blog.csdn.net/NoamaNelson/article/details/134461177