• 第五章. 可视化数据分析分析图表—常用图表的绘制1—折线图,柱形图


    第五章. 可视化数据分析图

    5.3 常用图表的绘制1—折线图,柱形图

    本节主要介绍常用图表的绘制,主要包括折线图,柱形图。

    1.折线图(matplotlib.pyplot.plot)

    折线图可以显示随时间而变化的连续数据,适用于显示在相同时间间隔下数据的趋势

    1).语法:

    matplotlib.pyplot.plot(x,y,format_string,**kwargs)
    
    • 1

    参数说明:
    x:x轴数据
    y:y轴数据
    format_string:控制曲线格式的字符串,包括颜色,线条样式,标记样式等
    **kwargs:键值参数,相当于一个字典,比如,输入参数为:(1,2,3,4,k,a=1,b=2,c=3),*args=(1,2,3,4,k),**kwargs={‘a’:1,‘b’:2,‘c’:3}

    2).示例:

    • 示例1:基本折线图
    import pandas as pd
    import matplotlib.pyplot as plt
    
    pd.set_option('display.unicode.east_asian_width', True)
    df = pd.read_excel('F:\\Note\\清单.xlsx', sheet_name='Sheet2')
    print(df)
    
    # 设置画布
    fig = plt.figure(figsize=(6, 4), facecolor='y')
    
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 解决中文乱码
    plt.rcParams['axes.unicode_minus'] = False  # 解决负号不显示的问题
    
    # X,Y轴刻度线的显示方向
    plt.rcParams['xtick.direction'] = 'in'
    plt.rcParams['ytick.direction'] = 'in'
    
    # 设置线
    plt.plot(df['姓名'], df['生物'], color='c', linestyle='-', marker='o', mfc='w')
    
    # 设置网格线
    plt.grid(color='0.5', linestyle='--', linewidth=1)
    
    # 设置x,y轴坐标
    plt.xlabel('姓名')
    plt.ylabel('分数')
    
    # 设置坐标轴刻度
    plt.xticks(df['姓名'])
    plt.yticks(range(0, 160, 10))
    
    # 设置文本标签
    for x, y in zip(df['姓名'], df['生物']):
        plt.text(x, y + 5, '%.2f' % y, ha='center', va='center', fontsize=8, color='darkorange')
    
    # 设置标题和图例
    plt.title('成绩统计表')
    
    # 设置图标图例
    plt.legend(['生物'],
               loc='upper right')  # 手动添加图例时,有时文本会显示不全,在文本后面加一个逗号(,)可解决,例如('图书采购价目',)
    
    # 调整图表与画布边缘间距
    plt.subplots_adjust(left=0.15, bottom=0.15, right=0.9, top=0.9)
    
    # 坐标轴的刻度线向内显示还是向外显示
    plt.tick_params(left=True, bottom=True, right=False, top=False)
    
    # 显示图像
    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
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    结果展示:
    在这里插入图片描述

    • 示例2:多折线图
    import pandas as pd
    import matplotlib.pyplot as plt
    
    pd.set_option('display.unicode.east_asian_width', True)
    df = pd.read_excel('F:\\Note\\清单.xlsx', sheet_name='Sheet2')
    print(df)
    
    # 设置画布
    fig = plt.figure(figsize=(6, 4), facecolor='y')
    
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 解决中文乱码
    plt.rcParams['axes.unicode_minus'] = False  # 解决负号不显示的问题
    
    # X,Y轴刻度线的显示方向
    plt.rcParams['xtick.direction'] = 'in'
    plt.rcParams['ytick.direction'] = 'in'
    
    # 设置线
    plt.plot(df['姓名'], df['生物'], color='m', linestyle=':', marker='o', mfc='w')
    plt.plot(df['姓名'], df['化学'], color='y', linestyle='--', marker='D', mfc='w')
    plt.plot(df['姓名'], df['物理'], color='0.5', linestyle='-', marker='d', mfc='w')
    
    # 设置网格线
    plt.grid(color='0.5', linestyle='--', linewidth=1)
    
    # 设置x,y轴坐标
    plt.xlabel('姓名')
    plt.ylabel('分数')
    
    # 设置坐标轴刻度
    plt.xticks(df['姓名'])
    plt.yticks(range(0, 160, 10))
    
    # 设置文本标签
    # str_name = {'生物', '化学', '物理'}
    # for i in str_name:
    #     for x, y in zip(df['姓名'], df[i]):
    #         plt.text(x, y, '%.2f' % y, ha='center', va='bottom', fontsize=7)
    
    # 设置标题和图例
    plt.title('成绩统计表')
    
    # 设置图标图例
    plt.legend(['生物', '化学', '物理'],
               loc='upper right')  # 手动添加图例时,有时文本会显示不全,在文本后面加一个逗号(,)可解决,例如('图书采购价目',)
    
    # 调整图表与画布边缘间距
    plt.subplots_adjust(left=0.15, bottom=0.15, right=0.9, top=0.9)
    
    # 坐标轴的刻度线向内显示还是向外显示
    plt.tick_params(left=True, bottom=True, right=False, top=False)
    
    # 显示图像
    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
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    结果展示:
    在这里插入图片描述

    2.柱形图(matplotlib.pyplot.bar)

    柱形图用来比较两个或以上的数据(不同时间或者不同条件),只有一个变量,通常用于较少数据集分析

    1).语法:

    matplotlib.pyplot.bar(x,height,width,bottom=None,*,align='center',data=None,**kwargs)
    
    • 1

    参数说明:
    x:x轴数据
    height:y轴数据
    width:柱子的宽度,默认值0.8
    bottom:标量或者数组,可选参数,柱形图的y坐标,默认值None
    *:星号本身不是参数,星号表示其后面的参数为命名关键字参数,命名关键字参数必须传入参数名,否则程序会出现错误
    align:对其方式:可选参数:center和edge,默认值center
    data:关键字参数,若给定一个数据参数,所有位置和关键字参数将会被替换
    **kwargs:关键字参数:其他可选参数,如color(颜色),alphs(透明度),label(每个柱子显示的标签)

    2).示例:

    • 示例1:基本柱形图
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    pd.set_option('display.unicode.east_asian_width', True)
    df = pd.read_excel('F:\\Note\\清单.xlsx', sheet_name='Sheet2')
    print(df)
    
    # 设置画布
    fig = plt.figure(figsize=(6, 4), facecolor='y')
    
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 解决中文乱码
    plt.rcParams['axes.unicode_minus'] = False  # 解决负号不显示的问题
    
    # X,Y轴刻度线的显示方向
    plt.rcParams['xtick.direction'] = 'in'
    plt.rcParams['ytick.direction'] = 'in'
    
    x_label = df['姓名']
    
    # 柱形图
    x_label = np.arange(len(x_label))  # x轴刻度标签位置
    width = 0.25  # 柱子的宽度
    
    plt.bar(x_label, df['生物'], width=width, color='orange')
    
    # 设置网格线
    plt.grid(axis='y', color='0.5', linestyle='--', linewidth=1)
    
    # 设置x,y轴坐标
    plt.xlabel('姓名')
    plt.ylabel('分数')
    
    # # 设置坐标轴刻度
    plt.xticks(x_label, df['姓名'])
    plt.yticks(range(0, 160, 10))
    
    # 设置文本标签
    
    for x, y in zip(x_label, df['生物']):
        plt.text(x, y, '%.1f' % y, ha='center', va='baseline', fontsize=7.5)
    
    # 设置标题和图例
    plt.title('成绩统计表')
    
    # 设置图标图例
    plt.legend(['生物'],
               loc='upper right')  # 手动添加图例时,有时文本会显示不全,在文本后面加一个逗号(,)可解决,例如('图书采购价目',)
    
    # 调整图表与画布边缘间距
    plt.subplots_adjust(left=0.15, bottom=0.15, right=0.9, top=0.9)
    
    # 坐标轴的刻度线向内显示还是向外显示
    plt.tick_params(left=True, bottom=True, right=False, top=False)
    
    # 显示图像
    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
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    结果展示:
    在这里插入图片描述

    • 示例2:多柱形图
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    pd.set_option('display.unicode.east_asian_width', True)
    df = pd.read_excel('F:\\Note\\清单.xlsx', sheet_name='Sheet2')
    print(df)
    
    # 设置画布
    fig = plt.figure(figsize=(6, 4), facecolor='y')
    
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 解决中文乱码
    plt.rcParams['axes.unicode_minus'] = False  # 解决负号不显示的问题
    
    # X,Y轴刻度线的显示方向
    plt.rcParams['xtick.direction'] = 'in'
    plt.rcParams['ytick.direction'] = 'in'
    
    x_label = df['姓名']
    
    # 柱形图
    x_label = np.arange(len(x_label))  # x轴刻度标签位置
    width = 0.25  # 柱子的宽度
    
    plt.bar(x_label - width, df['生物'], width=width, color='orange')
    plt.bar(x_label, df['化学'], width=width, color='skyblue')
    plt.bar(x_label + width, df['物理'], width=width, color='c')
    
    # 设置网格线
    plt.grid(axis='y', color='0.5', linestyle='--', linewidth=1)
    
    # 设置x,y轴坐标
    plt.xlabel('姓名')
    plt.ylabel('分数')
    
    # # 设置坐标轴刻度
    plt.xticks(x_label, df['姓名'])
    plt.yticks(range(0, 160, 10))
    
    # 设置文本标签
    str_name = ['生物', '化学', '物理']
    dis1 = x_label - width
    dis2 = x_label
    dis3 = x_label + width
    
    dis = [dis1, dis2, dis3]
    
    index = 0
    for i in str_name:
        for x, y in zip(x_label, df[i]):
            plt.text((dis[index][x]), y, '%.1f' % y, ha='center', va='baseline', fontsize=7.5)
        index = index + 1
    
    # 设置标题和图例
    plt.title('成绩统计表')
    
    # 设置图标图例
    plt.legend(['生物', '化学', '物理'],
               loc='upper right')  # 手动添加图例时,有时文本会显示不全,在文本后面加一个逗号(,)可解决,例如('图书采购价目',)
    
    # 调整图表与画布边缘间距
    plt.subplots_adjust(left=0.15, bottom=0.15, right=0.9, top=0.9)
    
    # 坐标轴的刻度线向内显示还是向外显示
    plt.tick_params(left=True, bottom=True, right=False, top=False)
    
    # 显示图像
    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
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68

    结果展示:
    在这里插入图片描述

    • 示例3:堆叠柱形图
    import pandas as pd
    import matplotlib.pyplot as plt
    
    pd.set_option('display.unicode.east_asian_width', True)
    df = pd.read_excel('F:\\Note\\清单.xlsx', sheet_name='Sheet2')
    print(df)
    
    # 设置画布
    fig = plt.figure(figsize=(6, 4), facecolor='y')
    
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 解决中文乱码
    plt.rcParams['axes.unicode_minus'] = False  # 解决负号不显示的问题
    
    # X,Y轴刻度线的显示方向
    plt.rcParams['xtick.direction'] = 'in'
    plt.rcParams['ytick.direction'] = 'in'
    
    x_label = df['姓名']
    
    # # 柱形图
    # x_label = np.arange(len(x_label))  # x轴刻度标签位置
    width = 0.35  # 柱子的宽度
    
    plt.bar(x_label, df['生物'], width=width, color='orange')
    plt.bar(x_label, df['化学'], width=width, color='skyblue',bottom=df['生物'])
    
    # 设置网格线
    plt.grid(axis='y', color='0.5', linestyle='--', linewidth=1)
    
    # 设置x,y轴坐标
    plt.xlabel('姓名')
    plt.ylabel('分数')
    
    # # 设置坐标轴刻度
    plt.xticks(x_label, df['姓名'])
    plt.yticks(range(0, 201, 10))
    
    # 设置文本标签
    for x, y in zip(x_label, df['生物'] + df['化学']):
        plt.text(x, y, '%.1f' % y, ha='center', va='baseline', fontsize=8, color='g')
    
    # 设置标题和图例
    plt.title('成绩统计表')
    
    # 设置图标图例
    plt.legend(['生物', '化学'],
               loc='upper right')  # 手动添加图例时,有时文本会显示不全,在文本后面加一个逗号(,)可解决,例如('图书采购价目',)
    
    # 调整图表与画布边缘间距
    plt.subplots_adjust(left=0.15, bottom=0.15, right=0.9, top=0.9)
    
    # 坐标轴的刻度线向内显示还是向外显示
    plt.tick_params(left=True, bottom=True, right=False, top=False)
    
    # 显示图像
    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
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    结果展示:
    请添加图片描述

    注意:代码中所涉及到的函数和参数,在图表的常用设置1图表的常用设置2 有所介绍

  • 相关阅读:
    iOS——仿写计算器
    《代码之丑》学习总结
    时间类(Date和Time)
    面试Python一定要记住的超基础知识点【速记】
    Spring Security CSRF 保护指南
    强大的Docker入门知识
    中国棉花行业兼并重组机会研究及决策咨询报告
    基于SSM的教学管理系统设计与实现
    RabbitMQ的安装与使用
    安全运营中心(SOC)技术框架
  • 原文地址:https://blog.csdn.net/weixin_45116749/article/details/128133046