• 《对比Excel,轻松学习Python数据分析》读书笔记------数据可视化


    13 数据可视化

    13.1 数据可视化的目的

    在信息呈现的三种表现形式中,

    最直观的是图。

    在这里插入图片描述

    数据可视化的目的,就是借助于图形化手段,清晰有效地传达与沟通信息。

    13.2 数据可视化的基本流程

    13.2.1 整理数据

    • 对数据进行规范
    • 明确可视化哪些数据
    • 提取需要可视化的数据

    13.2.2 明确目的

    • 思考本次可视化的目的
    • 斟酌展示的数据
    • 明确想要传达的信息

    13.2.3 寻找合适的表现形式

    • 针对本次可视化的目的选择合适的表现形式
    • 明确各类信息展示需要的图表种类(条形图,折线图,扇形图…)

    13.2.4 绘图

    • 依设计,对各类信息所需要的图表进行绘制

    • 查看实际效果,进行细化和调控

    13.3 图表的基本组成元素

    在这里插入图片描述

    元素含义
    画布绘图界面。即图表呈现的区域。
    坐标系用于标识变量。一块画布当中可以建立多个坐标系。坐标系分为直角坐标系,球坐标系和极坐标系三种,其中直角坐标系最常用。
    坐标轴坐标轴是坐标系中的概念,用以显示变量范围和确定数据点。二维直角坐标系有两根坐标轴。横轴x轴一般代表自变量,纵轴y轴一般代表因变量,且因变量一般不止一个。
    坐标轴标题顾名思义。即每根坐标轴的名称。用于显示坐标轴代表的变量的实际含义
    图表标题整个图表的名称。用于介绍整个图表展示的整体内容
    数据标签用于展示一个数据点的确切数值或意义
    数据表一般展示在图的下方。用于辅助图进行数据展示
    网格线网格线是坐标轴的一系列平行线。用于更加明确地揭示变量的数值所在范围
    图例用于分辨不同的因变量与自变量之间的图形。一般用符号和颜色来作图例。
    其他辅助线如误差线,极值线等。助力于信息表达

    13.4 Python的数据可视化基础

    在Excel中,只需"插入">“图表”,即可绘制各种图表。操作较为简单。下面均以Python的matplotlib库为例。

    13.4.1 导入相关库和显示设置

    import matplotlib.pyplot as plt  #导入matplotlib.pyplot并取别名plt
    
    plt.rcParams["font.sans-serif"] = 'SimHei'  # 设置默认字体为简黑,解决中文乱码问题
    plt.rcParams['axes.unicode_minus'] = False  # 解决负号无法显示的问题
    
    %matplotlib inline # 让图表直接在jupyter notebook中显示
    %config InlineBackend.figure_format='svg'  # 将显示的图表格式设置为矢量图,更加清晰
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    13.4.2 建立画布和坐标系

    画布 figure

    fig=plt.figure(num=None,
                   figsize=None,
                   dpi=None,
                   facecolor=None,
                   edgecolor=None
                  )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • num设置画布的标识。可以是数字或字符串。如果不传入,默认是从1开始递增的整数。
    • figsize设置画布大小,以英尺为单位。
    • dpi设置一英尺的像素大小。默认值100.即figsize·dpi为画布的像素大小
    • facecolor设置背景颜色
    • edgecolor设置边框颜色

    如:

    fig=plt.figure("图1",figsize=(10,8),dpi=40)
    # 
    • 1
    • 2
    颜色
    • RGB三元组,每个值在0-1之间:(0.1,0.2,0.3)
    • 十六进制RGB字符串:#13A4F7
    • 常见颜色的字符串:'b' 蓝色,'g' 绿色,'r' 红色,'c' 作为青色,'m' 洋红色,'y' 黄色,'k' 黑色,'w' 白色等

    坐标系 axis

    绘制坐标系的前提是,得有一块画布。

    add_subplot
    fig.add_subplot(nrows, ncols, index , projecttion='rectilinear')
    # 将画布划分为nrows·ncols个区域,在索引为index的区域绘制坐标系
    
    • 1
    • 2
    • projection可以设置坐标系的类型。默认为直角坐标。可用值为{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}。其中polar是极坐标,rectilinear是直角坐标

    如:

    fig=plt.figure("画布",figsize=(10,8),dpi=30)
    ax1=fig.add_subplot(3,4,(1,2),projection="aitoff")
    ax2=fig.add_subplot(3,4,(3,4),projection="lambert")
    ax3=fig.add_subplot(3,4,(5,6),projection='hammer')
    ax4=fig.add_subplot(3,4,(7,8),projection='mollweide')
    ax5=fig.add_subplot(3,4,(9,10),projection='polar')
    ax6=fig.add_subplot(3,4,(11,12),projection='rectilinear')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述

    数据分析一般以直角坐标系为主。

    plt.subplot2grid
    plt.subplot2grid(shape,loc,figure=None, projecttion='rectilinear')
    
    • 1
    • shape为一个元组,相当于add_subplotnrowsncols.将画布划分为nrows·ncols个区域
    • loc为一个元组。设置坐标系的行列位置。从0开始计数
    • figure指定画布。默认为当前使用的画布。

    如:

    fig=plt.figure("画布",figsize=(8,6),dpi=20)
    ax1=plt.subplot2grid((2,2),(0,0))
    ax2=plt.subplot2grid((2,2),(0,1),projection="polar")
    ax3=plt.subplot2grid((2,2),(1,0),projection="polar")
    ax4=plt.subplot2grid((2,2),(1,1))
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述

    plt.subplot
    plt.subplot(nrows, ncols, index , projecttion='rectilinear')
    
    • 1
    • add_subplot,只不过画布默认使用当前画布。
    plt.subplots

    在显示区一次性绘制多个坐标系,自动衡量画布大小并把画布返回

    fig,axes=plt.subplots(nrows, ncols)
    
    • 1

    如:

    fig,axes=plt.subplots(3,3)
    print(fig)
    # Figure(432x288)
    print(axes)
    """[[  ]
     [  ]
     [  ]]
    """
    
    # axes为列表,可索引到各个坐标系
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    在这里插入图片描述

    13.4.3 设置坐标轴

    创建完坐标系后,要立即设置坐标轴的格式。

    标题 label

    plt.xlabel(xlabel, fontdict=None,labelpad=None, *, loc=None, **kwargs)  # 设置当前坐标系的x轴标题
    plt.ylabel(ylabel, fontdict=None,labelpad=None, *, loc=None, **kwargs)	# 设置当前坐标系的y轴标题
    
    • 1
    • 2
    • xlabelylabel设置坐标轴标题的文字内容
    • labelpad设置文字离坐标轴的距离。默认值4
    • fontdict用于传入文字格式配置(字典)。
    • loc设置文字位于x轴方向的左侧('left'),中央('center'),还是右侧(right),y轴方向的顶端top,中央(center),还是底部(bottom).
    • **kwargs用于传入其他关于文字的参数。
    文字
    • fontsize:设置字体大小。可以为数字(像素)。也可以为预设的字符串,由小到大依次有 xx-small, x-small, small, medium, large,x-large, xx-large
    • color:设置字体颜色
    • fontstyle:设置字体样式。由倾斜程度依次有normal ,italic, oblique
    • fontweight:设置字体粗细。由细到粗依次有light, normal, medium, semibold, bold, heavy, black
    • backgroundcolor:设置字体的背景颜色
    • bbox:设置文字的边框信息,一个字典。键和值如下:
      • boxstyle:设置边框外形。square(矩形),round(圆角矩形),circle(圆形)
        • facecolor(简写fc):设置背景颜色
        • edgecolor(简写ec):设置边框线条颜色
        • edgewidth:设置边框线条大小

    如:

    fig = plt.figure(figsize=(8, 6))
    ax1 = fig.add_subplot(1, 3, 1)
    plt.xlabel("月份")
    plt.ylabel("销量")
    ax2 = fig.add_subplot(1, 3, 3)
    plt.xlabel("月份", labelpad=6, loc="right", fontsize=14, color='b')
    plt.ylabel("销量", labelpad=6, loc="top", fontsize=14, color='g')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述

    刻度 ticks

    plt.xticks(ticks=None, labels=None, **kwargs)
    plt.yticks(ticks=None, labels=None, **kwargs)
    
    • 1
    • 2
    • ticks设置刻度值。可传入由数值组成的列表类似的序列对象。
    • labels设置刻度文字。可传入字符串列表。
    • kwargs可传入文字相关的格式参数。
    fig = plt.figure(figsize=(4, 3))
    plt.xlabel("月份")
    plt.xticks(range(1,8),["一","二","三","四","五","六","七"])
    plt.ylabel("销量")
    plt.yticks(range(500,5000,500))
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述

    ticks传入空列表,可以达到隐藏坐标轴刻度线的作用:

    fig = plt.figure(figsize=(4, 3))
    plt.xlabel("月份")
    plt.xticks([])
    plt.ylabel("销量")
    plt.yticks([])
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述

    要调节刻度线,可以使用以下函数:

    plt.tick_params(axis, which, reset, direction, length, width, color, pad,
                    labelsize, labelcolor, top, bottom, left, right, labeltop,
                    labelbottom, labelledt, labelright)
    
    • 1
    • 2
    • 3
    • axis设置本次调节的轴:x轴('x'),y轴(y轴),两个都(both)
    • which设置本次调节的刻度线:主刻度线('major'),次刻度线(minor),两个都(both). (后面学)
    • reset设置是否重置所有之前的调节,以本次调节为准
    • direction设置刻度线的位置:在图中(in),在图外(out),图中图外都有(inout)
    • length设置刻度线的长度
    • width设置刻度线的宽度
    • color设置刻度线颜色
    • pad设置刻度线与刻度文字的距离。
    • labelsize设置刻度文字的大小
    • labelcolor设置刻度文字的颜色
    • top,bottom,left,right设置上下左右的刻度线是否显示
    • labeltop,labelbottom,labelleft,labelright设置上下左右的刻度文字是否显示

    如:

    fig = plt.figure(figsize=(4, 3))
    plt.xlabel("月份")
    plt.xticks(range(1, 8), ["一", "二", "三", "四", "五", "六", "七"])
    plt.ylabel("销量")
    plt.yticks(range(500, 5000, 500))
    plt.tick_params(axis="x", color="b", direction="in")
    plt.tick_params(axis="y",
                    color="g",
                    right=True,
                    labelright=True,
                    direction='inout')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这里插入图片描述

    坐标值的范围 lim

    x_bottom, x_top = plt.xlim()   # 获取当前x轴值的范围
    y_bottom, y_top = plt.ylim()   # 获取当前y轴值的范围
    
    plt.xlim(bottom,top)   # 设置x轴值的范围
    plt.ylim(bottom,top)	# 设置y轴值的范围
    
    • 1
    • 2
    • 3
    • 4
    • 5

    如:

    plt.ylim(0,8000)
    
    • 1

    在这里插入图片描述

    坐标轴的显示

    坐标轴默认都是显示的。

    plt.axis('on')  # 显示坐标轴
    plt.axis('off') # 不显示坐标轴
    
    • 1
    • 2

    如:

    fig = plt.figure(figsize=(4, 3))
    ax1 = fig.add_subplot(1, 2, 1)
    plt.xlabel("月份")
    plt.xticks(range(1, 8), ["一", "二", "三", "四", "五", "六", "七"])
    plt.ylabel("销量")
    plt.yticks(range(500, 5000, 500))
    plt.tick_params(axis="x", color="b", direction="in")
    plt.tick_params(axis="y",
                    color="g",
                    right=True,
                    labelright=True,
                    direction='inout')
    plt.plot(range(1, 8), [1200, 1300, 1200, 2600, 1789, 1800, 1345])   # 绘制折线图,之后会学习
    
    ax2 = fig.add_subplot(1, 2, 2)
    plt.xlabel("月份")
    plt.xticks(range(1, 8), ["一", "二", "三", "四", "五", "六", "七"])
    plt.ylabel("销量")
    plt.yticks(range(500, 5000, 500))
    plt.tick_params(axis="x", color="b", direction="in")
    plt.tick_params(axis="y",
                    color="g",
                    right=True,
                    labelright=True,
                    direction='inout')
    plt.plot(range(1, 8), [1200, 1300, 1200, 2600, 1789, 1800, 1345]) # 绘制折线图,之后会学习
    plt.axis('off')
    
    • 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

    在这里插入图片描述

    双轴 twins

    在绘制完主轴的图表后,可以切换次轴,再在原来的基础上再画另一幅图表。

    plt.twinx()  # 切换设置次y轴
    plt.twiny()  # 切换设置次x轴
    
    • 1
    • 2

    如:

    fig=plt.figure(figsize=(4,3))
    fig.add_subplot(1,1,1)
    plt.xlabel("月份")
    plt.xticks(range(1, 8), ["一", "二", "三", "四", "五", "六", "七"])
    plt.ylabel("月销量")
    plt.yticks(range(500, 5000, 500))
    plt.twiny()  # 切换设置次x轴
    plt.xlabel("周")
    plt.xticks(range(1, 8), ["一", "二", "三", "四", "五", "六", "日"])
    plt.twinx()	 # 切换设置次y轴
    plt.ylabel("日平均销量")
    plt.yticks(range(0, 1000, 100))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    在这里插入图片描述

    13.4.4 其他元素

    网格线 grid

    网格线用于延伸刻度线。网格线默认关闭。

    plt.grid(visible,which,axis,**kwargs)
    
    • 1
    • visible设置网格线可见
    • which设置延伸哪种刻度线。主刻度线('major'),次刻度线(minor),两个都(both).(目前暂未学习到)
    • axis设置延伸哪根轴上的刻度线。x轴('x'),y轴(y轴),两个都(both)
    • **kwargs用于传入一些线条样式相关的参数
    线条
    • linestyle设置线条类型。实线('solid'),点虚线('dotted'),破折线('dashed'),点划线('dashdot')
    • color设置线条颜色。
    • linewidth设置线条宽度。

    如:

    def draw_graph():
        plt.xlabel("月份")
        plt.xticks(range(1, 8), ["一", "二", "三", "四", "五", "六", "七"])
        plt.ylabel("销量")
        plt.yticks(range(500, 5000, 500))
        plt.tick_params(axis="x", color="b", direction="in")
        plt.tick_params(axis="y",
                        color="g",
                        right=True,
                        labelright=True,
                        direction='inout')
        plt.plot(range(1, 8), [1200, 1300, 1200, 2600, 1789, 1800, 1345])
    
    
    fig = plt.figure(figsize=(6, 8))
    ax1 = fig.add_subplot(2, 2, 1)
    draw_graph()
    plt.grid(visible=True, axis='y', linestyle='dotted', color='g')
    ax2 = fig.add_subplot(2, 2, 2)
    plt.grid(visible=True, axis='x', linestyle='dashed', color='y')
    draw_graph()
    ax3 = fig.add_subplot(2, 2, 3)
    plt.grid(visible=True, axis='y', linestyle='dashdot', color='r')
    draw_graph()
    ax4 = fig.add_subplot(2, 2, 4)
    plt.grid(visible=True, axis='x', linestyle='solid')
    draw_graph()
    
    • 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

    在这里插入图片描述

    图例 legend

    稍后讲解的各种绘图函数,都可以传入一个label参数来当做图例。

    下面的函数将在图中显示这些图例

    plt.legend(loc, ncol, fontsize, prop, facecolor, edgecolor, title,
               title_fontsize, shadow)
    
    • 1
    • 2
    • loc设置图例的显示位置。
    含义数字代码
    ‘best’自动选择最合适的位置0
    ‘upper right’右上角1
    ‘upper left’左上角2
    ‘lower left’左下角3
    ‘lower right’右下角4
    ‘right’右侧5
    ‘center left’左侧中心6
    ‘center right’右侧中心7
    ‘lower center’底部中心8
    ‘upper center’顶部中心9
    ‘center’中心10
    • ncol设置一行放几个图例
    • fontsize设置字体大小
    • prop传入字体配置字典。
    • facecolor设置背景色
    • edgecolor设置边框色
    • title设置图例的标题
    • title_fontsize设置标题字体大小
    • shadow设置图例框是否添加阴影

    如:

    def draw_graph():
        plt.xlabel("月份")
        plt.xticks(range(1, 8), ["一", "二", "三", "四", "五", "六", "七"])
        plt.ylabel("销量")
        plt.yticks(range(500, 5000, 500))
        plt.tick_params(axis="x", color="b", direction="in")
        plt.grid(visible=True, axis='x', linestyle='dotted')
        plt.plot(range(1, 8), [1300, 1700, 4500, 3700, 2500, 2000, 1800],
                 label="甲")
        plt.plot(range(1, 8), [1900, 2700, 3600, 3800, 1500, 2400, 1600],
                 label="乙")
        plt.plot(range(1, 8), [2300, 2700, 3500, 2700, 3500, 2100, 1900],
                 label="丙")
    
    
    fig = plt.figure(figsize=(10, 6))
    fig.add_subplot(1, 2, 1)
    draw_graph()
    plt.legend()
    fig.add_subplot(1, 2, 2)
    draw_graph()
    plt.legend(ncol=3, loc="lower center", shadow=True, title="部门")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    在这里插入图片描述

    图标标题 title

    plt.title(label, fontdict=None, loc=None, pad=None, **kwargs)
    
    • 1
    • label设置标题文字
    • fontdict传入字体设置字典
    • loc设置标题位置。中央(ceenter),左侧(left),右侧(right)。
    • pad设置标题文字离图表的距离
    • **kwargs传入其他与字体相关的参数

    如:

    fig = plt.figure(figsize=(4, 3))
    draw_graph()
    plt.legend()
    plt.title("2022年部门销量对比图")
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    数据标签 text

    plt.text(x,y,s,ha,va,fontsize,fontdict,**kwargs)
    
    • 1
    • x,y设置数据点的位置
    • s设置显示的标签
    • ha设置数据点相对于标签的水平位置。中(center),左(left),右(right)
    • va设置数据点相对于标签的垂直位置。中(center),上(top),下(bottom)
    • fontsize设置字体大小
    • fontdict传入字体设置字典
    • **kwargs传入其他与字体相关的参数

    如:

    fig = plt.figure(figsize=(4, 3))
    x = range(1, 8)
    y = [1300, 1700, 4500, 3700, 2500, 2000, 1800]
    plt.xlabel("月份")
    plt.xticks(x, ["一", "二", "三", "四", "五", "六", "七"])
    plt.ylabel("销量")
    plt.yticks(range(500, 5000, 500))
    plt.tick_params(axis="x", color="b", direction="in")
    plt.grid(visible=True, axis='x', linestyle='dotted')
    plt.title("月销量折线图")
    plt.plot(x, y)
    
    for i, j in zip(x, y):
        plt.text(i, j, j, ha="right", va="top")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这里插入图片描述

    图表注释 annotate

    plt.annotate(text,xy,xytext,arrowprops,**kwargs)
    
    • 1
    • text设置注释文本
    • xy设置要被注释的数据点的位置。二元组
    • xytext设置注释文本的位置
    • arrowprops传入箭头配置字典。
      • color设置箭头颜色
        • arrowstyle设置箭头样式。-,->,-[,<-,<->,<,fancy,simple,wedge
    • **kwargs传入其他与字体相关的参数

    如:

    plt.annotate("产业旺期", (3, 4500), (1, 3500),
                 arrowprops={
                     'arrowstyle': "<-",
                     'color': '#568970'
                 },
                 color='r')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在这里插入图片描述

    表格 table

    plt.table(cellText=None,
              cellColours=None,
              cellLoc='right',
              colWidths=None,
              rowLabels=None,
              rowColours=None,
              rowLoc='left',
              colLabels=None,
              colColours=None,
              colLoc='center',
              loc='bottom',
              bbox=None,
              **kwargs)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • cellText设置表格的内容。二维列表。
    • cellColours设置单元格的颜色。二维列表
    • cellLoc设置单元格内文字的对齐方式。左(left),中(center),右(right)
    • colWidths设置列宽。二维列表
    • rowLabels,colLabels设置行列索引
    • rowColours,colColours设置行列索引格的颜色
    • rowLoccolLoc设置行列索引格文字的对齐方式。左(left),中(center),右(right)
    • loc设置表格所处位置。同plt.legend()loc参数
    • bbox设置边框样式
    • **kwargs设置其他更多的表格和文字属性。

    如:

    fig = plt.figure(figsize=(6, 6))
    
    fig.add_subplot(4, 1, (1, 3))
    x = range(1, 8)
    y = [1300, 1700, 4500, 3700, 2500, 2000, 1800]
    plt.xlabel("月份")
    plt.xticks(x, ["一", "二", "三", "四", "五", "六", "七"])
    plt.ylabel("销量")
    plt.yticks(range(500, 5000, 500))
    plt.tick_params(axis="x", color="b", direction="in")
    plt.grid(visible=True, axis='x', linestyle='dotted')
    plt.title("月销量折线图")
    plt.plot(x, y)
    for i, j in zip(x, y):
        plt.text(i, j, j, ha="right", va="top")
    plt.annotate("产业旺期", (3, 4500), (1, 3500),
                 arrowprops={
                     'arrowstyle': "<-",
                     'color': '#568970'
                 },
                 color='r')
    
    fig.add_subplot(4, 1, 4)
    xcolor = ["blue", "blue", "green", "green", "green", "blue", "blue"]
    plt.table([x, y],
              cellLoc="center",
              rowLabels=["月份", "销量"],
              rowColours=["yellow", "red"],
              cellColours=[xcolor, xcolor],
              loc="center")
    plt.axis('off')
    
    • 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

    在这里插入图片描述

    水平线/垂直线 axhline/axvline

    plt.axhline(y,xmin,xmax,**kwargs)
    plt.axvline(x,ymin,ymax,**kwargs)
    
    • 1
    • 2
    • y设置水平线的y值,xmin,xmax在0-1间,为水平线的起始位置和终点位置占比
    • x设置垂直线的x值,ymin,ymax在0-1间,为水平线的起始位置和终点位置占比
    fig=plt.figure(figsize=(4,3))
    fig.add_subplot(1,1,1)
    plt.axhline(3, xmin=0.25, xmax=0.75)
    plt.axvline(3,ymin=0.4,ymax=0.6)
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述

    13.5 常用图表绘制

    13.5.1 折线图

    plt.plot(x, y, color, linestyle, linewidth, marker, markeredgecolor,
             markeredgewidth, markerfacecolor, markersize, label)
    
    • 1
    • 2
    • x设置横轴数据。列表数组型数据均可
    • y设置纵轴数据。列表数组型数据均可
    • color设置线条颜色,linestyle设置线条形状,linewidth设置线条宽度
    • label设置图例
    点标记
    • marker设置点的标记类型。
    含义含义
    .o圆圈
    ^ v < >上,下,左,右三角s正方形
    p五边形*五角星
    h六边形+十字
    xD d大菱形 小菱形
    _横线
    • markeredgecolor设置标记外边颜色
    • markeredgewidth设置标记外边线宽
    • markerfacecolor设置标记实心颜色
    • markersize设置标记大小

    如:

    fig = plt.figure(figsize=(4, 3))  # 创建画布
    plt.subplot(1, 1, 1)  # 创建坐标系
    
    # 准备数据
    df = pd.DataFrame({
        "月份": [1, 2, 3, 4, 5, 6, 7],
        "注册量": [900, 2300, 6900, 4500, 5200, 3400, 4200]
    })
    x = df["月份"]
    y = df["注册量"]
    
    # 绘图
    plt.plot(x,
             y,
             color="blue",
             linestyle="dashdot",
             marker=".",
             markeredgecolor="red",
             label="月注册量")
    
    # 坐标轴
    plt.xlabel(df.columns[0])
    plt.ylabel(df.columns[1])
    plt.xticks(x, ["一", "二", "三", "四", "五", "六", "七"])
    plt.yticks(range(0, 7001, 1000), [f"{i}人" for i in range(0, 7001, 1000)])
    
    # 数据标签
    for i, j in zip(x, y):
        plt.text(i, j, j, ha="right", va="top")
    
    # 网格线
    plt.grid(visible=True, axis="both", linestyle="solid")
    
    # 图例
    plt.legend()
    
    # 标题
    plt.title("2022年1-7月用户注册量")
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/2022年1-7月用户注册量.png")
    
    • 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

    在这里插入图片描述

    13.5.2 柱形图

    plt.bar(x,
            height,
            width=0.8,
            bottom=None,
            *,
            label=None,
            align='center',
            color=None,
            edgecolor=None,
            **kwargs,)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • x设置横轴数据。列表数组型数据均可
    • height设置纵轴数据。列表数组型数据均可
    • width设置柱形宽度。数字或列表数组型数据均可
    • bottom设置柱形的底部位置。数字或列表数组型数据均可
    • label设置图例名。
    • align设置柱形与x轴单位的对齐关系。中心对齐centeredge边缘对齐
    • color设置柱形颜色
    • edgecolor设置柱形边框颜色
    • *,**kwargs传入其他相关参数

    普通柱形图

    fig = plt.figure(figsize=(4, 3))  # 创建画布
    plt.subplot(1, 1, 1)  # 创建坐标系
    
    # 准备数据
    df = pd.DataFrame({
        "班级": [1, 2, 3, 4, 5, 6, 7,8],
        "人数": [54, 56, 48, 39, 51, 42, 36,45]
    })
    x = df["班级"]
    y = df["人数"]
    
    # 绘图
    plt.bar(x,y,width=0.6,color="darkblue",align="center",label="总人数")
    
    # 坐标轴
    plt.xlabel(df.columns[0])
    plt.ylabel(df.columns[1])
    plt.xticks(x, ["一", "二", "三", "四", "五", "六", "七","八"])
    plt.yticks(range(0, 61, 10), [f"{i}人" for i in range(0, 61, 10)])
    
    # 数据标签
    for i, j in zip(x, y):
        plt.text(i, j, j, ha="center", va="bottom",color="blue")
        
    # 图例
    plt.legend()
    
    # 标题
    plt.title("高三各班人数统计")
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/高三各班人数统计.png")
    
    • 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

    在这里插入图片描述

    簇状柱形图

    根据宽度width,控制柱形的水平位置(x)即可

    fig = plt.figure(figsize=(4, 3))  # 创建画布
    plt.subplot(1, 1, 1)  # 创建坐标系
    
    # 准备数据
    df = pd.DataFrame({
        "班级": [1, 2, 3, 4, 5, 6, 7, 8],
        "男生": [36, 36, 24, 12, 30, 38, 25, 35],
        "女生": [18, 20, 24, 27, 21, 4, 11, 10]
    })
    x = df["班级"]
    y1 = df["男生"]
    y2 = df["女生"]
    
    # 绘图
    width = 0.4
    plt.bar(x - width / 2,
            y1,
            width=width,
            color="darkblue",
            align="center",
            label="男生")
    
    plt.bar(x + width / 2,
            y2,
            width=width,
            color="darkred",
            align="center",
            label="女生")
    
    # 坐标轴
    plt.xlabel(df.columns[0])
    plt.ylabel("人数")
    plt.xticks(x, ["一", "二", "三", "四", "五", "六", "七", "八"])
    plt.yticks(range(0, 51, 10), [f"{i}人" for i in range(0, 51, 10)])
    
    # 数据标签
    for i, j1, j2 in zip(x, y1, y2):
        plt.text(i - width / 2, j1, j1, ha="center", va="bottom", color="blue")
        plt.text(i + width / 2, j2, j2, ha="center", va="bottom", color="red")
    
    # 图例
    plt.legend()
    
    # 标题
    plt.title("高三各班人数统计")
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/高三各班人数统计.png")
    
    • 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

    在这里插入图片描述

    堆积柱形图

    在同一水平位置(x)重复绘制y值即可

    fig = plt.figure(figsize=(4, 3))  # 创建画布
    plt.subplot(1, 1, 1)  # 创建坐标系
    
    # 准备数据
    df = pd.DataFrame({
        "月份": [1, 2, 3, 4, 5, 6, 7],
        "任务量": [1200, 1600, 1300, 1600, 1800, 1280, 1280],
        "完成量": [800, 1500, 900, 1000, 1720, 1200, 1100]
    })
    x = df["月份"]
    y1 = df["任务量"]
    y2 = df["完成量"]
    
    # 绘图
    plt.bar(x, y1, width=0.6, color="darkred", align="center", label="任务量")
    
    plt.bar(x, y2, width=0.6, color="darkblue", align="center", label="完成量")
    
    # 坐标轴
    plt.xlabel(df.columns[0])
    plt.ylabel("人数")
    plt.xticks(x, ["一", "二", "三", "四", "五", "六", "七"])
    plt.yticks(range(0, 2001, 250), [f"{i}件" for i in range(0, 2001, 250)])
    
    # 数据标签
    for i, j1, j2 in zip(x, y1, y2):
        plt.text(i, j1, j1, ha="center", va="bottom", color="red")
        plt.text(i, j2, j2, ha="center", va="top", color="yellow")
    
    # 图例
    plt.legend()
    
    # 标题
    plt.title("2022年1-7月任务完成度")
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/2022年1-7月任务完成度.png")
    
    • 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

    在这里插入图片描述

    13.5.3 条形图

    plt.barh(y,
            width,
            height=0.8,
            left=None,
            *,
            label=None,
            align='center',
            color=None,
            edgecolor=None,
            **kwargs,)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 调用方法类似plt.bar(),只不过方向调换了而已
    fig = plt.figure(figsize=(4, 3))  # 创建画布
    plt.subplot(1, 1, 1)  # 创建坐标系
    
    # 准备数据
    df = pd.DataFrame({
        "月份": [1, 2, 3, 4, 5, 6, 7],
        "任务量": [1200, 1600, 1300, 1600, 1800, 1280, 1280],
        "完成量": [800, 1500, 900, 1000, 1720, 1200, 1100]
    })
    y = df["月份"]
    x1 = df["任务量"]
    x2 = df["完成量"]
    
    # 绘图
    plt.barh(y, x1, height=0.6, color="darkred", align="center", label="任务量")
    
    plt.barh(y, x2, height=0.6, color="darkblue", align="center", label="完成量")
    
    # 坐标轴
    plt.ylabel(df.columns[0])
    plt.xlabel("件数")
    plt.yticks(x, ["一", "二", "三", "四", "五", "六", "七"])
    plt.xticks(range(0, 2001, 250), range(0, 2001, 250))
    
    # 数据标签
    for i, j1, j2 in zip(y, x1, x2):
        plt.text(j1, i, j1, ha="left", va="center", color="red")
        plt.text(j2, i, j2, ha="right", va="center", color="yellow")
    
    # 图例
    plt.legend()
    
    # 标题
    plt.title("2022年1-7月任务完成度")
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/2022年1-7月任务完成度.png")
    
    • 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

    在这里插入图片描述

    13.5.4 散点图/气泡图

    plt.scatter(x,
                y,
                s=None,
                c=None,
                marker=None,
                linewidths=None,
                *,
                edgecolors=None,
                **kwargs)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • x,y,x轴数据,y轴数据。列表数组型数据均可
    • s设置点的面积大小。可以是一个数,也可以是列表数组型数据
    • c设置点的颜色。可以是一个颜色,也可以是一组颜色。这里的颜色会自动映射,只需传入数字。
    • marker设置点的标记类型。同plt.plot()marker参数
    • linewidths设置点的边框颜色。可以是一个颜色,也可以是一组颜色
    • ***kwargs允许传入其他相关参数

    散点图

    fig = plt.figure(figsize=(4, 3))  # 创建画布
    plt.subplot(1, 1, 1)  # 创建坐标系
    
    # 准备数据
    df = pd.DataFrame({
        "年龄": [12, 13, 14, 15, 16, 17, 18, 19, 20],
        "平均年阅读量": [6.8, 7.1, 4.2, 5.0, 3.3, 2.1, 1.2, 7.6, 4.9]
    })
    x = df["年龄"]
    y = df["平均年阅读量"]
    
    # 绘图
    plt.scatter(x,y,s=20,c="blue",marker='o')
    
    # 坐标轴
    plt.xlabel(df.columns[0])
    plt.ylabel(df.columns[1])
    plt.xticks(x,x)
    plt.yticks(range(0, 9, 1), [f"{i}本" for i in range(0, 9, 1)])
    
    # 网格线
    plt.grid(visible=True, axis="both", linestyle="dashdot")
    
    
    # 标题
    plt.title("12-20青少年平均阅读量")
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/12-20青少年平均阅读量.png")
    
    • 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

    在这里插入图片描述

    气泡图

    只需调整s参数与c参数,使得各个点的面积不同即可

    # 绘图
    plt.scatter(x,
                y,
                s=[45 * i + 100 for i in y],
                c=[45 * i + 100 for i in y],
                marker='o')
    
    # 数据标签
    for i, j in zip(x, y):
        plt.text(i, j, j, ha="center", va="center", color='red',fontsize=8)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    在这里插入图片描述

    13.5.5 面积图

    plt.stackplot(x,y1,y2,y3,...,labels,colors,**kwargs,)
    
    • 1
    • x设置x轴数据
    • y1,y2,y3...设置y轴数据。各y轴数据对应同种颜色面积的上下值差
    • labels设置y轴数据们的图例。
    • colors设置面积的颜色。
    fig = plt.figure(figsize=(4, 3))  # 创建画布
    plt.subplot(1, 1, 1)  # 创建坐标系
    
    # 准备数据
    df = pd.DataFrame({
        "月份": [1, 2, 3, 4, 5, 6, 7],
        "安卓": [1000, 1200, 1400, 1200, 1000, 1200, 900],
        "Windows": [1400, 2000, 1300, 3400, 1200, 1400, 1100],
        "Mac": [1000, 900, 1400, 1500, 2100, 1700, 1800]
    })
    
    x = df["月份"]
    y1 = df["安卓"]
    y2 = df["Windows"]
    y3 = df["Mac"]
    
    # 绘图
    plt.stackplot(x,
                  y1,
                  y2,
                  y3,
                  labels=df.columns[1:4],
                  colors=['red', 'green', 'blue'])
    
    # 坐标轴
    plt.xlabel(df.columns[0])
    plt.ylabel("下载次数")
    plt.xticks(x, ["一", "二", "三", "四", "五", "六", "七"])
    plt.yticks(range(0, 6001, 1000), [f"{i}次" for i in range(0, 6001, 1000)])
    
    # 图例
    plt.legend()
    
    # 网格线
    plt.grid(visible=True, axis="both", linestyle="dotted")
    
    # 标题
    plt.title("2022年1-7月平台下载量")
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/2022年1-7月平台下载量")
    
    • 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

    在这里插入图片描述

    13.5.6 树地图

    绘制树地图需要导入另一个库squarify

    squarify.plot(sizes,label,color,value,edgecolor,linewidth)
    
    • 1
    • sizes设置绘图的数据
    • label设置各个类别的图例
    • color设置各个类别的颜色
    • value设置各个类别的数据标签
    • edgecolor设置边框颜色
    • linewidth设置边框宽度
    import squarify
    
    fig = plt.figure(figsize=(4, 3))  # 创建画布
    plt.subplot(1, 1, 1)  # 创建坐标系
    plt.axis('off') # 不显示坐标轴
    
    # 准备数据
    df = pd.DataFrame({
        "月份": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
        "人数": [800, 920, 1400, 1090, 400, 560, 2000, 940, 2010, 1400, 1109,1600]
    })
    x = df["月份"]
    y = df["人数"]
    
    # 绘图
    squarify.plot(y, label=[f"{i}月" for i in x], value=[f"{j}人" for j in y],edgecolor="white",linewidth=1)
    
    
    # 标题
    plt.title("xx学院出生月份分布")
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/xx学院出生月份分布.png")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    在这里插入图片描述

    13.5.7 雷达图

    雷达图是在极坐标系中作图。

    plt.polar(theta,r,color,marker,linewidth,**kwargs)
    
    • 1
    • theta传入角度
    • r传入半径
    • color设置线条颜色
    • marker设置线条样式
    • linewidth设置线条宽度
    • **kwargs传入取它相关参数
    import numpy as np
    
    fig = plt.figure(figsize=(4, 3))  # 创建画布
    plt.subplot(1, 1, 1, projection="polar")  # 创建极坐标系
    
    # 准备数据
    df = pd.DataFrame({
        "方面": ["物攻", "特攻", "物防", "特防", "速度"],
        "数值": [32, 23, 12, 30, 42]
    })
    x = list(df["方面"])
    x.append(x[0])
    y = list(df["数值"])
    y.append(y[0])
    angles = [i * 2 * np.pi / 5 for i in range(1, 6)]
    angles.append(angles[0])  # 最后一个数据等于最开始的一个,形成闭环
    
    # 绘图
    plt.polar(angles, y, color="blue", marker="o", markerfacecolor="red")
    
    # 坐标轴
    plt.xticks(angles, x)
    plt.yticks(range(0, 51, 10))
    
    # 标题
    plt.title("xxx宝可梦能力分布图")
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/xxx宝可梦能力分布图.png")
    
    • 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

    在这里插入图片描述

    13.5.8 箱形图

    plt.boxplot(x,
                vert=None,
                whis=None,
                widths=None,
                labels=None
                )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • x设置箱形图数据
    • vert设置箱形图方向。垂直方向True,水平方向False
    • whis设置分位线的位置,默认是上三分位和下三分位。可传入二元数组。数值在(0,100)间,代表百分比。
    • widths设置箱形图的宽度
    • labels设置图例
    fig = plt.figure(figsize=(4, 3))  # 创建画布
    plt.subplot(1, 1, 1)  # 创建坐标系
    
    # 准备数据
    df = pd.DataFrame({
        "语文": [110,120,120,109,103,123,112,98],
        "数学":[92,98,102,132,133,142,126,122],
        "英语":[102,132,121,109,78,98,121,142]
    })
    
    # 绘图
    plt.boxplot(df,widths=0.6,labels=df.columns)
    
    # 标题
    plt.title("语数英成绩分布")
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/语数英成绩分布.png")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这里插入图片描述

    13.5.9 饼图

    plt.pie(x,
            explode=None,
            labels=None,
            colors=None,
            autopct=None,
            pctdistance=0.6,
            shadow=False,
            labeldistance=1.1,
            startangle=0,
            radius=1,
            counterclock=True,
            wedgeprops=None,
            textprops=None,
            center=(0, 0),
            frame=False
            )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • x设置绘图数据
    • explode设置每一块饼离圆心的距离以突出某些区域
    • labels设置每一块饼的标签
    • colors设置每一块饼的颜色
    • autopct设置饼内数值的百分号形式
    • pctdistance设置数值距离圆心的距离
    • shadow设置是否有阴影
    • labeldistance设置饼标签距离圆心的距离
    • startangle设置饼图的初始角度
    • radius设置饼图半径
    • counterclock设置是否逆时针显示
    • wedgeprops设置饼图内外边界样式
    • textprops设置文字样式
    • center设置圆心位置
    • frame设置是否显示坐标轴
    fig = plt.figure(figsize=(4, 4))  # 创建画布
    plt.subplot(1, 1, 1)  # 创建坐标系
    
    # 准备数据
    df = pd.DataFrame({
        "种类": ["饮食", "娱乐", "教育", "生活缴费", "其他"],
        "支出": [1500, 200, 2000, 600, 200]
    })
    x = df["种类"]
    y = df["支出"]
    
    # 绘图
    plt.pie(y, labels=x, explode=[0, 0, 0.1, 0, 0], autopct="%.1f%%", shadow=True)
    
    # 标题
    plt.title("7月支出占比")
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/7月支出占比.png")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    在这里插入图片描述

    13.5.10 圆环图

    在扇形图的基础上进行改造,调整wedgeprop(内外边界)参数,可以绘制圆环图

    fig = plt.figure(figsize=(4, 3))  # 创建画布
    plt.subplot(1, 1, 1)  # 创建坐标系
    
    # 准备数据
    df = pd.DataFrame({
        "部门": [
            "甲",
            "乙",
            "丙",
            "丁",
        ],
        "任务量": [800, 1600, 1300, 1600],
        "完成量": [700, 1500, 900, 1200]
    })
    x = df["部门"]
    y1 = df["任务量"]
    y2 = df["完成量"]
    
    # 绘图
    plt.pie(y1,
            labels=x,
            radius=1.4,
            autopct="%.0f%%",
            wedgeprops=dict(width=0.7, edgecolor="white"))
    plt.pie(y2,
            radius=0.6,
            autopct="%.1f%%",
            wedgeprops=dict(width=0.5, edgecolor="white"))
    
    # 标题
    plt.title("2022年1-7月任务完成度", pad=25)
    
    #注释
    plt.annotate("完成量",
                 xy=(0.4, 0.1),
                 xytext=(1.7, 0.4),
                 arrowprops=dict(color="black", arrowstyle="<-"))
    plt.annotate("目标量",
                 xy=(1, -0.1),
                 xytext=(1.7, -0.4),
                 arrowprops=dict(color="black", arrowstyle="<-"))
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/2022年1-7月任务完成度.png")
    
    • 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

    在这里插入图片描述

    13.5.11 热力图

    plt.imshow(X,cmap=None)
    
    • 1
    • X为矩阵型数据。
    • cmap为颜色映射方案。可选值封装在plt.cm
    fig = plt.figure(figsize=(4, 3))  # 创建画布
    plt.subplot(1, 1, 1)  # 创建坐标系
    
    # 准备数据
    df = pd.DataFrame({
        "数学类": [120, 130],
        "软件工程": [360, 60],
        "土木工程": [370, 16],
        "汉语言文学": [120, 300]
    })
    
    # 绘图
    plt.imshow(df, cmap=plt.cm.coolwarm)
    plt.colorbar()  # 显示颜色映射条
    
    # 坐标轴
    plt.xticks(range(0, len(df.columns)), labels=df.columns, fontsize=8)
    plt.yticks([0, 1], labels=["男", "女"])
    
    # 标题
    plt.title("专业与男女数相关性")
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/专业与男女数相关性.png")
    
    • 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

    在这里插入图片描述

    13.6 使用样式

    matplotlib提供了很多成套的样式,可以直接拿来用。

    plt.style.available   # 查看可用样式
    
    • 1
    ['Solarize_Light2',
     '_classic_test_patch',
     '_mpl-gallery',
     '_mpl-gallery-nogrid',
     'bmh',
     'classic',
     'dark_background',
     'fast',
     'fivethirtyeight',
     'ggplot',
     'grayscale',
     'seaborn',
     'seaborn-bright',
     'seaborn-colorblind',
     'seaborn-dark',
     'seaborn-dark-palette',
     'seaborn-darkgrid',
     'seaborn-deep',
     'seaborn-muted',
     'seaborn-notebook',
     'seaborn-paper',
     'seaborn-pastel',
     'seaborn-poster',
     'seaborn-talk',
     'seaborn-ticks',
     'seaborn-white',
     'seaborn-whitegrid',
     'tableau-colorblind
    
    • 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

    如果想要使用某种样式,在程序的开头输入以下代码:

    plt.style.use(样式名)
    
    • 1

    如:

    plt.style.use('dark_background')
    
    plt.rcParams["font.sans-serif"] = 'SimHei'  # 设置字体为简黑,解决中文乱码问题
    plt.rcParams['axes.unicode_minus'] = False  # 解决负号无法显示的问题
    
    fig = plt.figure(figsize=(4, 3))  # 创建画布
    plt.subplot(1, 1, 1)  # 创建坐标系
    
    # 准备数据
    df = pd.DataFrame({
        "月份": [1, 2, 3, 4, 5, 6, 7],
        "注册量": [900, 2300, 6900, 4500, 5200, 3400, 4200]
    })
    x = df["月份"]
    y = df["注册量"]
    
    # 绘图
    plt.plot(x,
             y,
             color="blue",
             linestyle="dashdot",
             marker=".",
             markeredgecolor="red",
             label="月注册量")
    
    # 坐标轴
    plt.xlabel(df.columns[0])
    plt.ylabel(df.columns[1])
    plt.xticks(x, ["一", "二", "三", "四", "五", "六", "七"])
    plt.yticks(range(0, 7001, 1000), [f"{i}人" for i in range(0, 7001, 1000)])
    
    # 数据标签
    for i, j in zip(x, y):
        plt.text(i, j, j, ha="right", va="top")
    
    # 网格线
    plt.grid(visible=True, axis="both", linestyle="solid")
    
    # 图例
    plt.legend()
    
    # 标题
    plt.title("2022年1-7月用户注册量")
    
    # 显示或保存
    ## plt.show()  在jupyter之外的环境
    plt.savefig("./files/2022年1-7月用户注册量.png")
    
    • 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

    在这里插入图片描述

  • 相关阅读:
    迭代器的封装与反向迭代器
    如何选择优质的静动态住宅代理IP提供商?
    我的云栖大会之旅:见证云计算创新的15年
    土豆网鼠标经过显示遮罩---pink老师课程案例
    【数据结构】栈
    Python | 排列与组合
    详细介绍c++中的类
    如何给玩偶建模并让它跳个舞?
    fastadmin 后台添加视频
    超越datetime:Arrow,Python中的日期时间管理大师
  • 原文地址:https://blog.csdn.net/ncu5509121083/article/details/126272123