• 技术文章 >Python技术 >Python基础教程

    如何使用python绘制折线图?

    宋雪维宋雪维2021-02-24 16:50:58原创18988

    使用python绘制折线图过程

    1、导入库和设置输入折线图数据

    import numpy as np
    import matplotlib.pyplot as plt
    # x轴刻度标签
    x_ticks = ['a', 'b', 'c', 'd', 'e', 'f']
    # x轴范围(0, 1, ..., len(x_ticks)-1)
    x = np.arange(len(x_ticks))
    # 第1条折线数据
    y1 = [5, 3, 2, 4, 1, 6]
    # 第2条折线数据
    y2 = [3, 1, 6, 5, 2, 4]

    2、设置画布大小并绘制折线

    plt.figure(figsize=(10, 6))
    # 画第1条折线,参数看名字就懂,还可以自定义数据点样式等等。
    plt.plot(x, y1, color='#FF0000', label='label1', linewidth=3.0)
    # 画第2条折线
    plt.plot(x, y2, color='#00FF00', label='label2', linewidth=3.0)
    # 给第1条折线数据点加上数值,前两个参数是坐标,第三个是数值,ha和va分别是水平和垂直位置(数据点相对数值)。
    for a, b in zip(x, y1):
        plt.text(a, b, '%d'%b, ha='center', va= 'bottom', fontsize=18)
    # 给第2条折线数据点加上数值
    for a, b in zip(x, y2):
        plt.text(a, b, '%d'%b, ha='center', va= 'bottom', fontsize=18)
    # 画水平横线,参数分别表示在y=3,x=0~len(x)-1处画直线。
    plt.hlines(3, 0, len(x)-1, colors = "#000000", linestyles = "dashed")

    3、添加x轴和y轴刻度标签

    plt.xticks([r for r in x], x_ticks, fontsize=18, rotation=20)
    plt.yticks(fontsize=18)
    # 添加x轴和y轴标签
    plt.xlabel(u'x_label', fontsize=18)
    plt.ylabel(u'y_label', fontsize=18)

    4、绘制折线图标题和图例

    # 标题
    plt.title(u'Title', fontsize=18)
    # 图例
    plt.legend(fontsize=18)

    5、保存完成

    # 保存图片
    plt.savefig('./figure.pdf', bbox_inches='tight')
    # 显示图片
    plt.show()
    专题推荐:python基础
    品易云
    上一篇:python ChainMap的调用效率 下一篇:Python进行开发的两种方式

    相关文章推荐

    • python线程中deque如何使用?• python添加列表元素的多种方法• Counter在python中两种用法• OrderedDict在python字典的实现• Python如何捕获正在运行的CMD窗口内容?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网