【Python】matplotlib绘制折线图

一、绘制简单的折线图

import matplotlib.pyplot as plt
squares=[1,4,9,16,25]
plt.plot(squares)
plt.show()

我们首先导入模块pylot,并给他指定别名plt,然后创建列表,存储前述的平方数,再将这个列表传递给函数plot(),这个函数尝试根据这些数字绘制出有意义的图形。plot.show()打开matplotlib查看器,并显示绘制图形。

运行结果:

image

二、修改标签文字和线条粗细

#coding:UTF-8
import matplotlib.pyplot as plt
squares=[1,4,9,16,25]
plt.plot(squares,linewidth = 5)

#设置图形的标题,并给坐标轴加上标签
plt.title("Squares Numbers",fontsize=24)
plt.xlabel("Value",fontsize=14)
plt.ylabel("Square of value",fontsize=14)

#设置刻度表标记的大小
plt.tick_params(axis="both",labelsize=14)
plt.plot(squares)
plt.show()

title():给图表指定标题

xlabel():给X轴设置标题

ylabel():给Y轴设置标题

tick_params():设置刻度的样式

运行结果:

image 

校正图形

从上面的图形可以看出:折线图的终点4对应的平方为25,下面来修复这个问题

当你向plot()提供一系列数字时,它假设第一个数据点对应的x坐标轴值为0,但我们的第一个坐标轴对应的x轴为1,为了改变这种默认行为,我们可以给plot()同时提供输入值和输出值

#coding:UTF-8
import matplotlib.pyplot as plt
input_value = [1,2,3,4,5]
squares=[1,4,9,16,25]
plt.plot(input_value,squares,linewidth = 5)

#设置图形的标题,并给坐标轴加上标签
plt.title("Squares Numbers",fontsize=24)
plt.xlabel("Value",fontsize=14)
plt.ylabel("Square of value",fontsize=14)

#设置刻度表标记的大小
plt.tick_params(axis="both",labelsize=14)
plt.show()

运行结果:

image

原文地址:https://www.cnblogs.com/OliverQin/p/7956172.html