python 折线图标签_如何使用python绘制折线图?

本文介绍了如何使用Python的matplotlib库来绘制折线图,包括设置数据、画布大小、绘制折线、添加数据点标签、设定轴刻度以及添加图例等步骤,通过实例详细解析了绘制折线图的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

154a91f95845a518c2aa294a9ed10c03.png

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值