Python 绘制数据图表

  • matplotlib绘图库模块安装
  • pip install matplotlib
    

  • 导入pyplot子模块
  • import matplotlib.pyplot as plt
    
  • 官网:http://matplotlib.org
  • 官方文档:https://matplotlib.org/stable/index.html
  • 1. 绘制折线图

    1.1 绘制简单的折线图

    import matplotlib
    import matplotlib.pyplot as plt
    
    # 设置字体为微软雅黑,解决中文显示问题
    matplotlib.rc("font", family='Microsoft YaHei')
    
    # 1.准备数据
    squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    
    # 2.画线plot()
    # linewidth设置线条宽度
    plt.plot(squares, linewidth=2)  # 列表内的数据被视为y轴的值,x轴的值会根据列表值的索引位置自动产生
    
    # 3.设置x、y轴的最小刻度和最大刻度
    plt.axis([0, 10, 0, 100])  # 将x轴设为0~10,将y轴设为0~100
    
    # 4.设置标题及字体大小
    """
    title():图表标题,title(标题名称,fontsize=字体大小)
    xlabel():x轴标题
    ylabel():y轴标题
    """
    plt.title(label='0~10的平方', fontsize=18)
    plt.xlabel(xlabel='值', fontsize=15)
    plt.ylabel(ylabel='平方值', fontsize=15)
    
    # 5.设置坐标轴刻度
    """
    使用tick_params()方法设置:
        - 应用范围(axis):x-->应用到x轴,y-->应用到y轴,both-->应用到x轴和y轴
        - 坐标轴的刻度大小(labelsize)
        - 线条颜色(color)
    如:tick_params(axis='x', labelsize=10, color='green')
    """
    plt.tick_params(axis='both', labelsize=12, color='red', labelcolor='green')
    
    # 显示绘制的图形
    plt.show()
    

    效果:

    1.2 修改图表的初始值

    import matplotlib
    import matplotlib.pyplot as plt
    
    # 设置字体为微软雅黑,解决中文显示问题
    matplotlib.rc("font", family='Microsoft YaHei')
    
    # 1.准备数据
    squares = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    
    # 索引列表
    seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    # 2.画线plot()
    # linewidth设置线条宽度
    plt.plot(seq, squares, linewidth=2.5)
    
    # 设置标题及字体大小
    plt.title(label='1~10的平方', fontsize=18)
    plt.xlabel(xlabel='值', fontsize=15)
    plt.ylabel(ylabel='平方值', fontsize=15)
    
    # 5.设置坐标轴刻度
    plt.tick_params(axis='both', labelsize=12, color='red', labelcolor='green')
    
    # 显示绘制的图形
    plt.show()
    

    效果:

    1.3 多组数据的应用

    # author:mlnt
    # createdate:2022/8/17
    
    import matplotlib
    import matplotlib.pyplot as plt
    
    # 设置字体为微软雅黑,解决中文显示问题
    matplotlib.rc("font", family='Microsoft YaHei')
    
    # 1.准备数据
    data1 = [1, 4, 9, 16, 25, 36, 49, 64, 81]
    data2 = [1, 3, 5, 8, 13, 21, 34, 55, 89]
    
    # 索引列表
    seq = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    # 2.画线plot()
    # linewidth设置线条宽度
    plt.plot(seq, data1, seq, data2, linewidth=2.5)
    
    # 设置标题及字体大小
    plt.title(label='Test Chart', fontsize=18)
    plt.xlabel(xlabel='x-value', fontsize=14)
    plt.ylabel(ylabel='y-value', fontsize=14)
    
    # 5.设置坐标轴刻度
    plt.tick_params(axis='both', labelsize=12, color='red', labelcolor='green')
    
    # 显示绘制的图形
    plt.show()
    

    效果:

    1.4 设置线条颜色及样式

  • 设置颜色,可在plot()中添加参数:

  • ‘b’: blue
  • ‘c’: cyan
  • ‘g’: green
  • ‘k’: black
  • ‘m’: magenta
  • ‘r’: red
  • ‘w’: white
  • ‘y’: yellow
  • 设置线条样式:

  • '-‘或’solid’: 预设实线
  • '–‘或’dashed’: 虚线
  • '-.‘或’dashdot’: 虚点线
  • ':‘或’dotted’:点线
  • ‘.’:点标记
  • ‘,’:像素标记
  • ‘o’: 圆标记
  • ‘v’: 反三角标记
  • ‘^’: 三角标记
  • ‘s’:方形标记
  • ‘p’:五角标记
  • ‘*’: 星号标记
  • ‘+’:加号标记
  • ‘-’:减号标记
  • import matplotlib.pyplot as plt
    
    # 1.准备数据
    data1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]            # data1线条
    data2 = [1, 4, 9, 16, 25, 36, 49, 64, 81]      # data2线条
    data3 = [1, 3, 5, 8, 13, 21, 34, 55, 89]       # data3线条
    data4 = [1, 6, 12, 20, 30, 41, 56, 72, 90]     # data4线条
    
    # 索引列表
    seq = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    plt.plot(seq, data1, 'g--', seq, data2, 'r-.', seq, data3, 'b:', seq, data4, 'mp')
    
    # 设置标题及字体大小
    plt.title(label='Test Chart', fontsize=18)
    plt.xlabel(xlabel='x-value', fontsize=14)
    plt.ylabel(ylabel='y-value', fontsize=14)
    
    # 设置坐标轴刻度
    plt.tick_params(axis='both', labelsize=12, color='red')
    
    plt.show()
    

    效果:

    1.5 刻度设置

    import matplotlib
    import matplotlib.pyplot as plt
    
    # 设置字体为微软雅黑,解决中文显示问题
    matplotlib.rc("font", family='Microsoft YaHei')
    # 1.准备数据
    gold_medal = [15, 5, 16, 16, 28, 32, 51, 38, 26, 38]
    silver_medal = [8, 11, 22, 22, 16, 17, 21, 27, 18, 32]
    bronze_medal = [9, 12, 16, 12, 15, 14, 28, 23, 26, 18]
    
    # 索引列表
    year = [1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021]
    
    
    """
    设置刻度:
    - xticks():设置x轴刻度
    - yticks():设置y轴刻度
    """
    # 设置x轴刻度
    plt.xticks(year)
    
    # 设置线条样式
    plt.plot(year, gold_medal, '-*', year, silver_medal, '-o', year, bronze_medal, '-^')
    
    # 设置标题及字体大小
    plt.title('中国历届奥运会奖牌情况', fontsize=20)
    plt.xlabel('年份', fontsize=14)
    plt.ylabel('数量/枚', fontsize=14)
    # 设置坐标轴刻度
    plt.tick_params(axis='both', labelsize=12, color='red')
    # 显示图表
    plt.show()
    

    效果:

    1.6 图例legend()

    参数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
  • 将图例放在图表内
  • import matplotlib
    import matplotlib.pyplot as plt
    
    # 设置字体为微软雅黑,解决中文显示问题
    matplotlib.rc("font", family='Microsoft YaHei')
    # 1.准备数据
    gold_medal = [15, 5, 16, 16, 28, 32, 51, 38, 26, 38]
    silver_medal = [8, 11, 22, 22, 16, 17, 21, 27, 18, 32]
    bronze_medal = [9, 12, 16, 12, 15, 14, 28, 23, 26, 18]
    
    # 索引列表
    year = [1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021]
    
    
    """
    设置刻度:
    - xticks():设置x轴刻度
    - yticks():设置y轴刻度
    """
    # 设置x轴刻度
    plt.xticks(year)
    
    # 设置线条样式
    line_gold, = plt.plot(year, gold_medal, '-*', label='gold_medal')
    line_silver, = plt.plot(year, silver_medal, '-o', label='silver_medal')
    line_bronze, = plt.plot(year, bronze_medal, '-^', label='bronze_medal')
    
    # 设置图例
    """
    参数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
    """
    plt.legend(handles=[line_gold, line_silver, line_bronze], loc='best')
    # 放在图表内的右上角
    # plt.legend(handles=[line_gold, line_silver, line_bronze], loc=1)
    # 放在图表内的左上角
    # plt.legend(handles=[line_gold, line_silver, line_bronze], loc='upper left')
    # 放在图表内的左下角
    # plt.legend(handles=[line_gold, line_silver, line_bronze], loc=3)
    # 放在图表内的右下角
    # plt.legend(handles=[line_gold, line_silver, line_bronze], loc=4)
    
    # 放在图表内的左侧中央
    # plt.legend(handles=[line_gold, line_silver, line_bronze], loc='center left')
    # 放在图表内的右侧中央
    # plt.legend(handles=[line_gold, line_silver, line_bronze], loc='center right')
    # 放在图表内的底部正中
    # plt.legend(handles=[line_gold, line_silver, line_bronze], loc='lower center')
    # 放在图表内的顶部正中
    # plt.legend(handles=[line_gold, line_silver, line_bronze], loc='upper center')
    
    # 设置标题及字体大小
    plt.title('中国历届奥运会奖牌情况', fontsize=20)
    plt.xlabel('年份', fontsize=14)
    plt.ylabel('数量/枚', fontsize=14)
    # 设置坐标轴刻度
    plt.tick_params(axis='both', labelsize=12, color='red')
    # 显示图表
    plt.show()
    

    效果:

  • 将图例放在图表外,使用savefig()方法保存图片文件

    # author:mlnt
    # createdate:2022/8/17
    import matplotlib
    import matplotlib.pyplot as plt
    
    # 设置字体为微软雅黑,解决中文显示问题
    matplotlib.rc("font", family='Microsoft YaHei')
    # 1.准备数据
    gold_medal = [15, 5, 16, 16, 28, 32, 51, 38, 26, 38]
    silver_medal = [8, 11, 22, 22, 16, 17, 21, 27, 18, 32]
    bronze_medal = [9, 12, 16, 12, 15, 14, 28, 23, 26, 18]
    
    # 索引列表
    year = [1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021]
    
    
    """
    设置刻度:
    - xticks():设置x轴刻度
    - yticks():设置y轴刻度
    """
    # 设置x轴刻度
    plt.xticks(year)
    
    # 设置线条样式
    line_gold, = plt.plot(year, gold_medal, '-*', label='gold_medal')
    line_silver, = plt.plot(year, silver_medal, '-o', label='silver_medal')
    line_bronze, = plt.plot(year, bronze_medal, '-^', label='bronze_medal')
    
    # 设置图例
    # bbox_to_anchor()设置锚点,即图例位置
    # 在图表内,左下角位置为(0,0),右上角位置为(1,1)
    plt.legend(handles=[line_gold, line_silver, line_bronze], loc='best', bbox_to_anchor=(1, 1))
    
    # 设置在图表与Figure 1之间留白
    # h_pad/w_pad分别设置高度/宽度的留白
    plt.tight_layout(pad=2)
    
    
    # 设置标题及字体大小
    plt.title('中国历届奥运会奖牌情况', fontsize=20)
    plt.xlabel('年份', fontsize=14)
    plt.ylabel('数量/枚', fontsize=14)
    # 设置坐标轴刻度
    plt.tick_params(axis='both', labelsize=12, color='red')
    
    # 保存图片文件,使用savefig()方法保存图片文件,需放在show()的前面,表示先存储再显示图表
    plt.savefig('medal_chart.jpg', bbox_inches='tight')  # bbox_inches='tight'将图表的多余空间删除
    
    # 显示图表
    plt.show()
    

    效果:

  • 2. 绘制散点图

    2.1 基本散点图的绘制

  • 绘制一个点
  • """
    scatter(x, y, s, c)
    s: 绘图点的大小
    c:颜色
    """
    import matplotlib.pyplot as plt
    
    # 在坐标轴(5,5)绘制一个点
    plt.scatter(5, 5)
    plt.show()
    

    效果:

  • 绘制系列点

    # author:mlnt
    # createdate:2022/8/17
    """
    scatter(x, y, s, c)
    s: 绘图点的大小
    c:颜色
    """
    import matplotlib.pyplot as plt
    
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签
    plt.rcParams['axes.unicode_minus'] = False
    
    medal = [32, 28, 54, 50, 59, 63, 100, 88, 70, 88]
    # 索引列表
    year = [1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021]
    
    # 设置x轴刻度
    plt.xticks(year)
    
    plt.scatter(x=year, y=medal, s=20, c='green')
    
    # 设置标题及字体大小
    plt.title('中国历届奥运会奖牌情况', fontsize=20)
    plt.xlabel('年份', fontsize=14)
    plt.ylabel('数量/枚', fontsize=14)
    # 设置坐标轴刻度
    plt.tick_params(axis='both', labelsize=12, color='red')
    plt.show()
    

    效果:

  • 2.2 设置绘制区间

    **axis()**设置绘图区间:

  • axis([xmin, xmax, ymin, ymax])
  • xmin/xmax:x轴的最小/最大区间
  • ymin/ymxa:y轴的最小/最大区间
  • # author:mlnt
    # createdate:2022/8/17
    """
    axis()设置绘图区间:
    axis([xmin, xmax, ymin, ymax])
    xmin/xmax:x轴的最小/最大区间
    ymin/ymxa:y轴的最小/最大区间
    """
    
    import matplotlib.pyplot as plt
    
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    
    x = [i for i in range(1, 101)]
    y = [i**2 for i in x]
    
    # 设置绘图区间
    plt.axis([0, 100, 0, 10000])
    plt.scatter(x=x, y=y, s=20, c='green')
    
    # 设置标题及字体大小
    plt.title('1-100的平方', fontsize=20)
    plt.xlabel('数值', fontsize=14)
    plt.ylabel('平方值', fontsize=14)
    # 设置坐标轴刻度
    plt.tick_params(axis='both', labelsize=12, color='red')
    plt.show()
    

    效果:

    2.3 绘制波形

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 10, 500)
    # 绘制sin()和cos()的波形变化
    y1 = np.sin(x)
    y2 = np.cos(x)
    plt.scatter(x, y1, color=(0.5, 0.8, 0.6))
    plt.scatter(x, y2)
    plt.show()
    

    效果:

    2.4 创建不等宽的散点图

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.linspace(0, 5, 500)
    y = 1 - 0.5*np.abs(x-2)
    lwidths = (1+x)**2
    plt.scatter(x=x, y=y, s=lwidths, color=(0.6, 0.8, 0.9))
    plt.show()
    

    效果:

    2.5 色彩映射

    import matplotlib.pyplot as plt
    import numpy as np
    
    
    x = np.arange(100)
    plt.scatter(x=x, y=x, c=x, cmap='rainbow')
    plt.show()
    

    效果:

    2.6 利用随机数绘制散点图

    import matplotlib.pyplot as plt
    import numpy as np
    
    while True:
        x = np.random.random(100)
        y = np.random.random(100)
        t = x
        plt.scatter(x, y, s=100, c=t, cmap='brg')
        plt.show()
        is_exit = input('是否继续?(y/n)')
        if is_exit.upper() == 'N':
            break
    

    2.7 利用随机数实现位置的移动

    # author:mlnt
    # createdate:2022/8/17
    import random
    
    import matplotlib.pyplot as plt
    
    
    def loc(index):
        """处理坐标的移动"""
        x_mov = random.choice([-3, 3])
        xloc = x[index - 1] + x_mov
        y_mov = random.choice([-5, -1, 1, 5])
        yloc = y[index - 1] + y_mov
        x.append(xloc)
        y.append(yloc)
    
    
    num = 8000
    x = [0]
    y = [0]
    
    while True:
        for i in range(1, num):
            loc(i)
    
        t = x
        plt.scatter(x, y, s=2, c=t, cmap='brg')
        # plt.axes().get_xaxis().set_visible(False)  # 隐藏y坐标
        # plt.axes().get_yaxis().set_visible(False)  # 隐藏y坐标
        # 隐藏坐标轴。
        plt.axis('off')
        plt.savefig('image.png', bbox_inches='tight', pad_inches=0)
        plt.show()
        is_exit = input('是否继续?(y/n)')
        if is_exit.upper() == 'N':
            break
        else:
            x[0] = x[num - 1]
            y[0] = y[num - 1]
            del x[1:]
            del y[1:]
    

    3. 绘制多个图表

    3.1 一个程序绘制多个图表

    # author:mlnt
    # createdate:2022/8/17
    import matplotlib.pyplot as plt
    
    # 1.准备数据
    data1 = [1, 4, 9, 16, 25, 36, 49, 64, 81]
    data2 = [1, 3, 5, 8, 13, 21, 34, 55, 89]
    
    # 索引列表
    seq = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    
    # 创建图表1
    plt.figure(1)
    # 画线plot()
    plt.plot(seq, data1, '-*')
    
    # 创建图表2
    plt.figure(2)
    plt.plot(seq, data2, '-o')
    # 设置标题及字体大小
    plt.title(label='Test Chart 2', fontsize=18)
    plt.xlabel(xlabel='x-value', fontsize=14)
    plt.ylabel(ylabel='y-value', fontsize=14)
    
    # 5.设置坐标轴刻度
    plt.tick_params(axis='both', labelsize=12, color='red', labelcolor='green')
    
    # 显示绘制的图形
    plt.show()
    

    效果:

    3.2 含有子表的图表

    subplot(x1, x2, x3)

  • x1: 上下(垂直)方向绘制图表数
  • x2:左右(水平)方向绘制图表数
  • x3:表示这是第几张
  • 一个Figure内绘制上下子图

    # author:mlnt
    # createdate:2022/8/17
    """
    subplot(x1, x2, x3)
    x1: 上下(垂直)方向绘制图表数
    x2:左右(水平)方向绘制图表数
    x3:表示这是第几张
    """
    import matplotlib.pyplot as plt
    
    # 1.准备数据
    data1 = [1, 4, 9, 16, 25, 36, 49, 64, 81]
    data2 = [1, 3, 5, 8, 13, 21, 34, 55, 89]
    
    # 索引列表
    seq = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    # 在一个Figure内绘制上下子图
    plt.subplot(2, 1, 1)
    # 画线plot()
    plt.plot(seq, data1, '-*')
    
    plt.subplot(2, 1, 2)
    plt.plot(seq, data2, '-o')
    # 设置标题及字体大小
    plt.xlabel(xlabel='x-value', fontsize=14)
    plt.ylabel(ylabel='y-value', fontsize=14)
    
    # 设置坐标轴刻度
    plt.tick_params(axis='both', labelsize=12, color='red', labelcolor='green')
    
    # 显示绘制的图形
    plt.show()
    

    效果:

  • 一个Figure内绘制左右子图

    # author:mlnt
    # createdate:2022/8/17
    """
    subplot(x1, x2, x3)
    x1: 上下(垂直)方向绘制图表数
    x2:左右(水平)方向绘制图表数
    x3:表示这是第几张
    """
    import matplotlib.pyplot as plt
    
    # 1.准备数据
    data1 = [1, 4, 9, 16, 25, 36, 49, 64, 81]
    data2 = [1, 3, 5, 8, 13, 21, 34, 55, 89]
    
    # 索引列表
    seq = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    # 在一个Figure内绘制上下子图
    plt.subplot(2, 1, 1)
    # 画线plot()
    plt.plot(seq, data1, '-*')
    
    plt.subplot(2, 1, 2)
    plt.plot(seq, data2, '-o')
    # 设置标题及字体大小
    plt.xlabel(xlabel='x-value', fontsize=14)
    plt.ylabel(ylabel='y-value', fontsize=14)
    
    # 设置坐标轴刻度
    plt.tick_params(axis='both', labelsize=12, color='red', labelcolor='green')
    
    # 显示绘制的图形
    plt.show()
    

    效果:

  • 4. 绘制直方图

    # author:mlnt
    # createdate:2022/8/17
    """
    bar(x, height, width)
    x: 序列,x轴位置
    height:序列数值大小
    width:直方图的宽度
    """
    import matplotlib.pyplot as plt
    import numpy as np
    
    plt.rcParams['font.sans-serif'] = ['SimHei'] # 显示中文标签
    plt.rcParams['axes.unicode_minus'] = False
    
    medal = [32, 28, 54, 50, 59, 63, 100, 88, 70, 88]
    x = np.arange(len(medal))
    # 索引列表
    year = [1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021]
    
    plt.bar(x, medal, width=0.5)
    
    # 设置标题及字体大小
    plt.title('中国历届奥运会奖牌情况', fontsize=20)
    plt.xlabel('年份', fontsize=14)
    plt.ylabel('数量/枚', fontsize=14)
    plt.xticks(x, year)
    # 设置坐标轴刻度
    plt.tick_params(axis='both', labelsize=12, color='red')
    plt.show()
    

    效果:

    # author:mlnt
    # createdate:2022/8/17
    import matplotlib.pyplot as plt
    import numpy as np
    
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    
    # 1.准备数据
    labels = [1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2021]
    gold_medal = [15, 5, 16, 16, 28, 32, 51, 38, 26, 38]
    silver_medal = [8, 11, 22, 22, 16, 17, 21, 27, 18, 32]
    bronze_medal = [9, 12, 16, 12, 15, 14, 28, 23, 26, 18]
    
    x = np.arange(len(labels))  # x轴位置
    width = 0.3  # 直方图的宽度
    
    fig, ax = plt.subplots()
    rects1 = ax.bar(x - width, gold_medal, width, label='gold_medal')
    rects2 = ax.bar(x, silver_medal, width, label='silver_medal')
    rects3 = ax.bar(x + width, bronze_medal, width, label='bronze_medal')
    
    # 设置标题及字体大小
    ax.set_xlabel('年份', fontsize=14)
    ax.set_ylabel('数量/枚', fontsize=14)
    ax.set_title('中国历届奥运会奖牌情况', fontsize=20)
    ax.set_xticks(x, labels)
    # 设置图例
    ax.legend()
    
    ax.bar_label(rects1, padding=3)
    ax.bar_label(rects2, padding=3)
    ax.bar_label(rects3, padding=3)
    
    fig.tight_layout()
    
    plt.show()
    

    效果:

    5. 使用CSV文件绘制图表

    # author:mlnt
    # createdate:2022/8/17
    import csv
    
    import matplotlib
    import matplotlib.pyplot as plt
    
    matplotlib.rc("font", family='Microsoft YaHei')
    
    filename = 'score.csv'
    
    with open(file=filename) as csvFile:    # 打开csv文件
        csvReader = csv.reader(csvFile)    # 创建reader对象
        headerRow = next(csvReader)   # 读取文件下一行
        print(headerRow)  # ['学号', '姓名', '语文', '数学', '英语', '物理', '化学', '生物']
        # 设置空列表
        names, Chinese, Math, English, Physics, Chemistry, Biology = [], [], [], [], [], [], []
        for row in csvReader:
            # 将数据添加到列表
            names.append(row[1])
            Chinese.append(int(row[2]))
            Math.append(int(row[3]))
            English.append(int(row[4]))
            Physics.append(int(row[5]))
            Chemistry.append(int(row[6]))
            Biology.append(int(row[7]))
        print(f'语文:{Chinese}')
        print(f'数学:{Math}')
        print(f'英语:{English}')
        print(f'物理:{Physics}')
        print(f'化学:{Chemistry}')
        print(f'生物:{Biology}')
    
    # 绘制语文成绩
    # 设置绘图区大小
    fig = plt.figure(dpi=80, figsize=(12, 8))
    # 设置线条样式
    line_Chinese, = plt.plot(names, Chinese, '-*', label='Chinese')
    line_Math, = plt.plot(names, Math, '-o', label='Math')
    line_English, = plt.plot(names, English, '-p', label='English')
    line_Physics, = plt.plot(names, Physics, '-s', label='Physics')
    line_Chemistry, = plt.plot(names, Chemistry, '-v', label='Chemistry')
    line_Biology, = plt.plot(names, Biology, '-^', label='Biology')
    # 设置图例
    plt.legend(handles=[line_Chinese, line_Math, line_English, line_Physics, line_Chemistry, line_Biology], loc='best')
    # 旋转
    fig.autofmt_xdate(rotation=60)
    plt.title('成绩分析', fontsize=20)
    plt.xlabel('学员', fontsize=14)
    plt.ylabel('分数', fontsize=14)
    plt.tick_params(axis='both', labelsize=12, color='red')
    plt.show()
    

    score.csv:

    效果:

    # author:mlnt
    # createdate:2022/8/17
    import csv
    from datetime import datetime
    
    import matplotlib
    import matplotlib.pyplot as plt
    
    matplotlib.rc("font", family='Microsoft YaHei')
    
    filename = 'temperature.csv'
    
    with open(file=filename) as csvFile:    # 打开csv文件
        csvReader = csv.reader(csvFile)    # 创建reader对象
        headerRow = next(csvReader)   # 读取文件下一行
        # print(headerRow)
        # 设置空列表
        dates, lowTemps, highTemps, averageTemps = [], [], [], []
        for row in csvReader:
            try:
                # 将日期字符串转成对象
                currentDate = datetime.strptime(row[0], '%Y/%m/%d')
                # 设置最低温度
                # 需要转换成数字类型,y轴才能进行排序
                lowTemp = float(row[1])
                # 设置最高温度
                highTemp = float(row[2])
                # 设置平均温度
                averageTemp = float(row[3])
            except Exception as e:
                print('有缺值', e)
            else:
                # 将数据添加到列表
                dates.append(currentDate)
                lowTemps.append(lowTemp)
                highTemps.append(highTemp)
                averageTemps.append(averageTemp)
        print(f'最低温度:{lowTemps}')
        print(f'最高温度:{highTemps}')
        print(f'平均温度:{averageTemps}')
    
    
    # # 设置绘图区大小
    fig = plt.figure(dpi=80, figsize=(12, 8))
    # 设置线条样式
    line_highTemps, = plt.plot(dates, highTemps, '-*', label='highTemps')
    line_lowTemps, = plt.plot(dates, lowTemps, '-o', label='lowTemps')
    line_averageTemps, = plt.plot(dates, averageTemps, '-p', label='averageTemps')
    # 设置图例
    plt.legend(handles=[line_lowTemps, line_averageTemps, line_highTemps], loc='best')
    # 旋转
    fig.autofmt_xdate(rotation=60)
    plt.title('Weather Report', fontsize=20)
    plt.xlabel('Date', fontsize=12)
    plt.ylabel('Temperature (C)', fontsize=14)
    plt.tick_params(axis='both', labelsize=12, color='red')
    plt.show()
    

    temperature.csv:

    效果:


    参考:

  • 官网:http://matplotlib.org
  • 官方文档:https://matplotlib.org/stable/index.html
  • 色彩映射:http://matplotlib.org/examples/color/colormaps_reference.html
  • https://blog.csdn.net/weixin_46233323/article/details/108038706
  • https://blog.csdn.net/weixin_43838785/article/details/104515455
  • https://blog.csdn.net/weixin_41783077/article/details/110734759
  • https://www.pudn.com/news/62623526dfdd9a1c0c529522.html
  • https://www.yzlfxy.com/jiaocheng/python/430158.html
  • https://www.zhihu.com/question/506015285
  • 物联沃分享整理
    物联沃-IOTWORD物联网 » Python 绘制数据图表

    发表评论