美文网首页python学习笔记Python
【python实战】matplotlib绘图(一)

【python实战】matplotlib绘图(一)

作者: Hobbit的理查德 | 来源:发表于2020-05-12 22:08 被阅读0次

    上次用pyecharts画了地图,【python实战】 pyecharts绘制地图
    虽然很好看,但是,考虑到渲染成图片时间比较长,因此,要是要批量作图的话,还是用matplotlib比较好,就像之前的Python批量word报告(带图)【思路篇】
    ,也是用的matplotlib。

    matplotlib算是很底层的包了,好处在于个性化设置上更灵活,缺点可能是要写的代码更多些吧,但是,总的来说,瑕不掩瑜。

    在学着用matplotlib作图的时候,主要是看matplotlib(https://matplotlib.org/index.html)里面的例子以及相应的文档。但不得不说,里面的文档真的挺难看的,pyecharts的就好看多了。另外就是加上搜索引擎了。

    这里放两个最近用到的图。

    1.条形图(broken_barh)

    broken_barh.png
    import matplotlib.pyplot as plt
    import matplotlib
    import matplotlib.lines as lines
    
    # 颜色转换
    def RGB_to_Hex(tmp):
        rgb = tmp.split(',')#将RGB格式划分开来
        strs = '#'
        for i in rgb:
            num = int(i)#将str转int
            #将R、G、B分别转化为16进制拼接转换并大写
            strs += str(hex(num))[-2:].replace('x','0').upper()
        return strs
    
    #设置字体、图形样式
    # sns.set_style("whitegrid")
    matplotlib.rcParams['font.sans-serif'] = ['SimHei']
    matplotlib.rcParams['font.family']='sans-serif'
    matplotlib.rcParams['axes.unicode_minus'] = False
    
    # 数据
    data={
            "data": [
                {"name":'全省',"5pct": 354, "mean":500,"95pct":684},
                {"name":'全市',"5pct": 342, "mean":511,"95pct":668},
                {"name":'A县',    "5pct": 327, "mean":514,"95pct":661}
            ],
        }
    
    # 数据设置
    ylabel=[d["name"] for d in data['data']]
    pct5=[d["5pct"] for d in data['data']]
    pct95=[d["95pct"] for d in data['data']]
    mean=[d["mean"] for d in data['data']]
    xbar=[(d["5pct"],d["95pct"]-d["5pct"]) for d in data['data']]
    
    # 属性设置
    yticks=[5,10,15]
    xlim=(min(pct5)-100,max(pct95)+100)
    colors=[RGB_to_Hex('255,140,0'),RGB_to_Hex('107,142,35'),RGB_to_Hex('116,162,221')]
    barheight=2
    
    # 作图
    # 设置图形大小
    plt.rcParams['figure.figsize'] = (6,2.5) 
    fig, ax = plt.subplots()
    for i in range(len(xbar)):
        ax.broken_barh([xbar[i]],(4+i*5,barheight),facecolors=(colors[i]))
        # 加标签
        ax.text(pct5[i]-40,yticks[i]-0.2,str(pct5[i]),size=10)
        ax.text(pct95[i]+10,yticks[i]-0.2,str(pct95[i]),size=10)
        ax.text(mean[i]-30,yticks[i]-0.2,str(mean[i]),size=10,color='black')
        # 加竖线
        line = lines.Line2D([mean[i],mean[i]], [4+i*5,4+i*5+barheight],
                        lw=1, color='black', axes=ax)
        ax.add_line(line)
    
    # 去掉边框
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    
    #设置x轴取值范围,y轴间隔及标签
    ax.set_xlim(xlim)
    ax.set_yticks(yticks)
    ax.set_yticklabels(ylabel)
    
    plt.savefig("broken_barh.png",dpi=600,bbox_inches = 'tight')
    plt.show()
    

    2.散点图(scatter)

    scatter.png
    import matplotlib.pyplot as plt
    import matplotlib
    import matplotlib.lines as lines
    from matplotlib.ticker import FuncFormatter
    
    # 颜色转换
    def RGB_to_Hex(tmp):
        rgb = tmp.split(',')#将RGB格式划分开来
        strs = '#'
        for i in rgb:
            num = int(i)#将str转int
            #将R、G、B分别转化为16进制拼接转换并大写
            strs += str(hex(num))[-2:].replace('x','0').upper()
        return strs
    
    #设置字体、图形样式
    # sns.set_style("whitegrid")
    matplotlib.rcParams['font.sans-serif'] = ['SimHei']
    matplotlib.rcParams['font.family']='sans-serif'
    matplotlib.rcParams['axes.unicode_minus'] = False
    
    # 数据(太多了,就只放三条吧)
    data={
            "data": [
            {"校间差异":0.135311972763609,"全省其他县":0,"你市各县":577.362102747501,"你市":0},
            {"校间差异":0.0616036942022612,"全省其他县":0,"你市各县":546.788848220486,"你市":0},
            {"校间差异":0.209066958823479,"全省其他县":0,"你市各县":517.929672671431,"你市":0}
        }
    
    # 数据设置
    x=[d["校间差异"] for d in data['data']]
    y1=[d["全省其他县"] for d in data['data'] ]
    y2=[d["你市各县"] for d in data['data']]
    y3=[d["你市"] for d in data['data']]
    label=["全省其他县","你市各县","你市"]
    
    
    # 作图
    # 设置图形大小
    plt.rcParams['figure.figsize'] = (8,6) 
    fig, ax = plt.subplots()
    ax.scatter(x,y1,c=RGB_to_Hex('79,129,189'),label=label[0])
    ax.scatter(x,y2,c=RGB_to_Hex('0,176,80'),label=label[1])
    ax.scatter(x,y3,c=RGB_to_Hex('228,108,10'),marker='^',label=label[2])
    
    # 去掉边框
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    
    #添加图例
    ax.legend(loc=9,ncol=3,edgecolor='grey',bbox_to_anchor=(0.5,1.1))
    
    #设置y轴取值范围
    ylim=[400,600]
    xlim=[0,0.4]
    ax.set_ylim(ylim)
    ax.set_xlim(xlim)
    
    # x轴以百分比的形式呈现
    def to_percent(temp, position):
        return '%.2f'%(10*temp) + '%'
    plt.gca().xaxis.set_major_formatter(FuncFormatter(to_percent))
    
    # 添加x和y轴名称
    ax.set_xlabel('校间差异',weight='bold',size=12)
    ax.set_ylabel('语文成绩',weight='bold',size=12,rotation='vertical')
    
    # 加虚线
    linecolor=RGB_to_Hex('79,129,189')
    linestyle='--'
    line_pos=[0.1,0.2,450,550]
    for i in range(2):
        line = lines.Line2D([line_pos[i],line_pos[i]],ylim,lw=0.5, color=linecolor, axes=ax,linestyle=linestyle)
        ax.add_line(line)
    for i in range(2,4):
        line = lines.Line2D(xlim,[line_pos[i],line_pos[i]],lw=0.5, color=linecolor, axes=ax,linestyle=linestyle)
        ax.add_line(line)
    
    # 添加文本
    ax.text(0,ylim[1]-10,'校间差异小,\n语文成绩高',size=12,color=RGB_to_Hex('79,129,189'),fontweight='bold')
    ax.text(0,ylim[0]+10,'校间差异小,\n语文成绩低',size=12,color='red',fontweight='bold')
    ax.text(xlim[1]-0.04,ylim[0]+10,'校间差异大,\n语文成绩低',size=12,color='red',fontweight='bold')
    ax.text(xlim[1]-0.04,ylim[1]-10,'校间差异大,\n语文成绩高',size=12,color='red',fontweight='bold')
    
    plt.savefig("scatter.png",dpi=600,bbox_inches = 'tight')
    plt.show()
    

    相关文章

      网友评论

        本文标题:【python实战】matplotlib绘图(一)

        本文链接:https://www.haomeiwen.com/subject/rpqwnhtx.html