zoukankan      html  css  js  c++  java
  • matplotlib模块

    mat plot lib库 --》画图

    matplotlib官方文档:https://matplotlib.org/contents.html?v=20190307135750

    matplotlib是一个绘图库,它可以创建常用的统计图,包括条形图、箱型图、折线图、散点图、饼图和直方图

    from matplotlib import pyplot as plt
    from matplotlib.font_manager import FontProperties # 修改字体
    font = FontProperties(fname='')
    clac = []
    stydents = []
    pt.bar(clas,students)
    plt.show()
    
    #图像标注参数
    设置图像标题:plt.title()
    设置x轴名称:plt.xlabel()
    设置y轴名称:plt.ylabel()
    设置X轴范围:plt.xlim()
    设置Y轴范围:plt.ylim()
    设置X轴刻度:plt.xticks()
    设置Y轴刻度:plt.yticks()
    设置曲线图例:plt.legend()
    
    
    #plot函数参数
    线型linestyle(-,-.,--,..)
    点型marker(v,^,s,*,H,+,x,D,o,…)
    颜色color(b,g,r,y,k,w,…)
    
    #饼图
    import numpy as np
    import matplotlib.pyplot as plt
    from pylab import mpl
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    
    fig, ax = plt.subplots(subplot_kw=dict(aspect="equal"))
    
    recipe = ['优', '良', '轻度污染', '中度污染', '重度污染', '严重污染', '缺']
    
    data = [2, 49, 21, 9, 11, 6, 2]
    colors = ['lime', 'yellow', 'darkorange', 'red', 'purple', 'maroon', 'grey']
    wedges, texts, texts2 = ax.pie(data,
                                   wedgeprops=dict(width=0.5),
                                   startangle=40,
                                   colors=colors,
                                   autopct='%1.0f%%',
                                   pctdistance=0.8)
    plt.setp(texts2, size=14, weight="bold")
    
    bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
    kw = dict(xycoords='data',
              textcoords='data',
              arrowprops=dict(arrowstyle="->"),
              bbox=None,
              zorder=0,
              va="center")
    
    for i, p in enumerate(wedges):
        ang = (p.theta2 - p.theta1) / 2. + p.theta1
        y = np.sin(np.deg2rad(ang))
        x = np.cos(np.deg2rad(ang))
        horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
        connectionstyle = "angle,angleA=0,angleB={}".format(ang)
        kw["arrowprops"].update({"connectionstyle": connectionstyle})
        ax.annotate(recipe[i],
                    xy=(x, y),
                    xytext=(1.25 * np.sign(x), 1.3 * y),
                    size=16,
                    horizontalalignment=horizontalalignment,
                    fontproperties=font,
                    **kw)
    
    ax.set_title("饼图示例",fontproperties=font)
    
    plt.show()
    # plt.savefig('jiaopie2.png')
    

    )

    #matplotlib的应用
    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    %matplotlib inline
    
    # 找到自己电脑的字体路径,然后修改字体路径
    font = FontProperties(fname='/Library/Fonts/Heiti.ttc')
    
    header_list = ['方程组', '函数', '导数', '微积分', '线性代数', '概率论', '统计学']
    py3_df = pd.read_excel('py3.xlsx', header=None,
                           skiprows=[0, 1], names=header_list)
    # 处理带有NaN的行
    py3_df = py3_df.dropna(axis=0)
    print(py3_df)
    
    # 自定义映射
    map_dict = {
        '不会': 0,
        '了解': 1,
        '熟悉': 2,
        '使用过': 3,
    }
    
    for header in header_list:
        py3_df[header] = py3_df[header].map(map_dict)
    
    unable_series = (py3_df == 0).sum(axis=0)
    know_series = (py3_df == 1).sum(axis=0)
    familiar_series = (py3_df == 2).sum(axis=0)
    use_series = (py3_df == 3).sum(axis=0)
    
    unable_label = '不会'
    know_label = '了解'
    familiar_label = '熟悉'
    use_label = '使用过'
    for i in range(len(header_list)):
        bottom = 0
    
        # 描绘不会的条形图
        plt.bar(x=header_list[i], height=unable_series[i],
                width=0.60, color='r', label=unable_label)
        if unable_series[i] != 0:
            plt.text(header_list[i], bottom, s=unable_series[i],
                     ha='center', va='bottom', fontsize=15, color='white')
        bottom += unable_series[i]
    
        # 描绘了解的条形图
        plt.bar(x=header_list[i], height=know_series[i],
                width=0.60, color='y', bottom=bottom, label=know_label)
        if know_series[i] != 0:
            plt.text(header_list[i], bottom, s=know_series[i],
                     ha='center', va='bottom', fontsize=15, color='white')
        bottom += know_series[i]
    
        # 描绘熟悉的条形图
        plt.bar(x=header_list[i], height=familiar_series[i],
                width=0.60, color='g', bottom=bottom, label=familiar_label)
        if familiar_series[i] != 0:
            plt.text(header_list[i], bottom, s=familiar_series[i],
                     ha='center', va='bottom', fontsize=15, color='white')
        bottom += familiar_series[i]
    
        # 描绘使用过的条形图
        plt.bar(x=header_list[i], height=use_series[i],
                width=0.60, color='b', bottom=bottom, label=use_label)
        if use_series[i] != 0:
            plt.text(header_list[i], bottom, s=use_series[i],
                     ha='center', va='bottom', fontsize=15, color='white')
    
        unable_label = know_label = familiar_label = use_label = ''
    
    plt.xticks(header_list, fontproperties=font)
    plt.ylabel('人数', fontproperties=font)
    plt.title('Python3期数学摸底可视化', fontproperties=font)
    plt.legend(prop=font, loc='upper left')
    plt.show()
    

    )

    #折线图
    import numpy as np
    from numpy.random import randn
    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    %matplotlib inline
    font = FontProperties(fname='/Library/Fonts/Heiti.ttc')
    
    # 修改背景为条纹
    plt.style.use('ggplot')
    
    np.random.seed(1)
    
    # 使用numpy的累加和,保证数据取值范围不会在(0,1)内波动
    plot_data1 = randn(40).cumsum()
    
    plot_data2 = randn(40).cumsum()
    plot_data3 = randn(40).cumsum()
    plot_data4 = randn(40).cumsum()
    
    plt.plot(plot_data1, marker='o', color='red', linestyle='-', label='红实线')
    plt.plot(plot_data2, marker='x', color='orange', linestyle='--', label='橙虚线')
    plt.plot(plot_data3, marker='*', color='yellow', linestyle='-.', label='黄点线')
    plt.plot(plot_data4, marker='s', color='green', linestyle=':', label='绿点图')
    
    # loc='best'给label自动选择最好的位置
    plt.legend(loc='best', prop=font)
    plt.show()
    

    )

    #散点图 + 直线图
    import numpy as np
    from numpy.random import randn
    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    %matplotlib inline
    font = FontProperties(fname='/Library/Fonts/Heiti.ttc')
    
    # 修改背景为条纹
    plt.style.use('ggplot')
    
    x = np.arange(1, 20, 1)
    print(x)
    [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]
    # 拟合一条水平散点线
    np.random.seed(1)
    y_linear = x + 10 * np.random.randn(19)
    
    # 拟合一条x²的散点线
    y_quad = x**2 + 10 * np.random.randn(19)
    
    # s是散点大小
    fig = plt.figure()
    ax1 = fig.add_subplot(121)
    plt.scatter(x, y_linear, s=30, color='r', label='蓝点')
    plt.scatter(x, y_quad, s=100, color='b', label='红点')
    
    ax2 = fig.add_subplot(122)
    plt.plot(x, y_linear, color='r')
    plt.plot(x, y_quad, color='b')
    
    # 限制x轴和y轴的范围取值
    plt.xlim(min(x) - 1, max(x) + 1)
    plt.ylim(min(y_quad) - 10, max(y_quad) + 10)
    fig.suptitle('散点图+直线图', fontproperties=font, fontsize=20)
    ax1.set_title('散点图', fontproperties=font)
    ax1.legend(prop=font)
    ax2.set_title('直线图', fontproperties=font)
    plt.show()
    

    )

  • 相关阅读:
    Git(五):Git分支管理策略
    Git(四):Git远程操作详解
    Git(三):Git 使用规范流程
    Git(二):常用 Git 命令清单
    Git(一):Eclipse中配置Git
    (一)Spring’s MVC Architecture
    Maven(九)”编码 gbk 的不可映射字符“ 问题解决方案
    Maven(八) Maven项目和testng结合应用
    Maven(七) maven 常用命令
    Maven(四-2) Maven pom.xml 配置详解
  • 原文地址:https://www.cnblogs.com/shaozheng/p/11609036.html
Copyright © 2011-2022 走看看