zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python绘制折线图

Python 绘制 折线图
2023-06-13 09:15:02 时间

折线图常用与展示数据的连续变化趋势。Python可以使用matplotlib库绘制折线图,并对折线图进行自定义美化。

绘制折线图

绘制折线图,分为准备数据、绘制图表和展示图表三个步骤。

准备数据

折线图,通常用来展示数据随时间的变化趋势。 x、y轴的数据都应该存储在列表中,并且两个列表中元素的个数必须相同。

绘制图表

py

pyplot.plot(data_x, data_y)

绘制折线图,需要使用pyplot模块中的plot()函数,参数分别为x轴、y轴数据。

py

from matplotlib import pyplot
pyplot.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'simhei']
data_x = ['一月', '二月', '三月', '四月', '五月']
data_y = [2, 12, 20, 25, 28]
pyplot.plot(data_x, data_y)
pyplot.show()

给图表添加标题和坐标轴标签。 添加标题:

py

pyplot.title('折线图')

添加标签:

py

pyplot.xlabel('x轴标签') 
pyplot.ylabel('y轴标签')

输入样例:

py

from matplotlib import pyplot
pyplot.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'simhei']
data_x = ['一月', '二月', '三月', '四月', '五月']
data_y = [2, 12, 20, 25, 28]
pyplot.plot(data_x, data_y)
pyplot.title('折线图')
pyplot.xlabel('x轴标签')
pyplot.ylabel('y轴标签')
pyplot.show()

输出样例:

展示图表

py

pyplot.show()

复式折线图

为了进行对比而将多条折线绘制在一起的折线图,叫做复式折线图。

绘制复式折线图

多次调用plot()函数 输入样例:

py

from matplotlib import pyplot
pyplot.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'simhei']
data_x = ['一月', '二月', '三月', '四月', '五月']
data_y1 = [2, 12, 20, 25, 28]
data_y2 = [10, 15, 22, 23, 25]
pyplot.plot(data_x, data_y1)
pyplot.plot(data_x, data_y2)
pyplot.title('折线图')
pyplot.xlabel('x轴标签')
pyplot.ylabel('y轴标签')
pyplot.show()

输出样例:

当图表中有多条折线时,程序会默认给每条折线分配不同的颜色,第一条为蓝色,第二条为橙色。我们可以添加图例,来进行区分。

添加图例

pyplot.legend([折线名称])

将折线的名称以列表的形式填写在括号中。列表中的元素顺序与个数要和折线保持一致。

输入样例:

py

from matplotlib import pyplot
pyplot.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'simhei']
data_x = ['一月', '二月', '三月', '四月', '五月']
data_y1 = [2, 12, 20, 25, 28]
data_y2 = [10, 15, 22, 23, 25]

pyplot.plot(data_x, data_y1)
pyplot.plot(data_x, data_y2)
pyplot.legend(['折线1', '折线2'])
pyplot.title('折线图')
pyplot.xlabel('x轴标签')
pyplot.ylabel('y轴标签')
pyplot.show()

输出样例:

折线样式

在复式折线图中,为了方便区分,我们可以设置每条折线的样式。

pyplot.plot(data_x, data_y, color=颜色, linestyle=线形)

matplotlib库有很多种颜色和线形的选择。

输入样例:

py

from matplotlib import pyplot
pyplot.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'simhei']
data_x = ['一月', '二月', '三月', '四月', '五月']
data_y1 = [2, 12, 20, 25, 28]
data_y2 = [10, 15, 22, 23, 25]

pyplot.plot(data_x, data_y1, color='purple', linestyle='--')
pyplot.plot(data_x, data_y2, color='green', linestyle='-.')
pyplot.legend(['折线1', '折线2'])
pyplot.title('折线图')
pyplot.xlabel('x轴标签')
pyplot.ylabel('y轴标签')
pyplot.show()

输出样例:

列表生成式

列表b = [元素操作部分 for i in 列表a]

程序会生成一个新列表,然后从列表a中依次取出每 一个元素,并对元素进行操作,存入新列表中。

使用列表生成式可以对列表中的每个元素进行操作。

py

a = ['1', '2', '3', '4']
b = [int(i) for i in a]
print(a)
print(b)

输出样例:

[‘1’, ‘2’, ‘3’, ‘4’] [1, 2, 3, 4]