品易云推流 关闭
文章详情页
文章 > Python基础教程 > 如何使用python绘制折线图?

如何使用python绘制折线图?

头像

宋雪维

2021-02-24 16:50:5819396浏览 · 0收藏 · 0评论

使用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()
关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图