python matplotlib 绘制折线图

在 matplotlib 官网教程中,可以绘制诸如折线图、柱状图、饼图等常规图外,还有可以绘制动态图、散点图、等高线图、帽子图、多个子图等

接下来,我们将继续学习matplotlib 图表绘制具体的功能实操,掌握针对不同图表的绘制

 

1. 折线图概述

1.1什么是折线图?

  • 折线图是在坐标中通过线条升降的方式展示随着某种变化而变化的连续性数据
  • 通过折线的起伏表示数据的增减变化的情况
  • 折线图可以拆分为动态折线图、依存关系折线图和次数分布折线图

1.2折线图使用场景

折线图自身的线条的变化,可以在图表中清晰读取到数据变化情况,可以运用的场景特点如下

  • 描绘统计事项总体指标的动态
  • 研究对象间的依存关系
  • 总体中各个部分的分配情况
  • 适合大量数据展示其趋势变化

1.3绘制折线图步骤

  • 导入matplotlib.pyplot模块
  • 准备数据,可以使用numpy/pandas整理数据
  • 调用pyplot.plot()绘制折线图

1.4案例展示

接下来我们使用折线图来展示从 10份 所有文章访问量数据展示

所有的案例用到的数据如下:

import random


x_data = ["10月{}日".format(i+1) for i in range(30)]

y_view = [random.randint(50,200) for i in range(30)]

展示10月份数据折线图:

import matplotlib.pyplot as plt
import random


plt.rcParams["font.sans-serif"]=['SimHei']
plt.rcParams["axes.unicode_minus"]=False

x_data = ["10月{}日".format(i+1) for i in range(30)]

y_view = [random.randint(50,200) for i in range(30)]

plt.figure(figsize=(20,5),dpi=90)

plt.plot(x_data,y_view)

plt.xticks(rotation=45)
plt.title("访问量分析")
plt.xlabel("日期")
plt.ylabel("访问量")

plt.show()

 

2. 折线2D属性

2.1linestyle:折线样式

 

属性值 说明
"-" 、"solid" 默认实线显示
"--"、"dashed" 虚线
"-." "dashdot" 点划线
":"、"dotted" 虚线
"None" """"

2.2color:折线颜色

颜色简称:

属性值 说明 属性值 说明
"b"/"bule" 蓝色 "m"/"magenta" 品红
"g" /"green" 绿色 "y"/"yellow" 黄色
"r"/"red" 红色 "k"/"black" 黑色
"c"/"cyan" 青色 "w"/"white" 白色

rgb

  • 格式形式:(r,g,b) 或者(r,g,b,a)
  • 取值范围:r,g,b,a 取值范围在[0,1]之间
  • [0,1]之间的浮点数的字符串形式,0表示黑色,1表示白色

2.3marker:坐标值标记

  • marker 标记物通常在折线图plot、散点图scatter和误差图errorbar上应用
  • marker 提供多达40个标记的样式可供选择,具体详情看见marker官方说明
  • marker 在图表中常用的有如下:

 

属性值 说明 属性值 说明
"o" ⏺️圆圈标记 "8" 八边形
"v" 倒三角标记 "s" ⏹️正方形标记
"^" 正三角标记 "*" ⭐星号
"<" ◀️左三角标记 "+" ➕加号
">" ▶️右三角标记 "x" X星星
"1" 向下Y标记 "D" 钻石标记
"2" 向上Y标记 " "
"3" 向左Y标记 "_" _水平线标记
"4" 向右Y标记 "p" ⭐五角星标记

标记还提供其他方法

  • markeredgecolor:标记边界颜色
  • markeredgewidth:标记宽度
  • markfacecorlor:标记填充色
  • markersize:标记大小

2.4fillstyle:标记填充方法

 

属性值 说明
"full" 整个标记
"left" 左边标记一半
"right" 右边标记一半
"bottom" 底部标记一半
"top" 顶部标记一半
"none" 无填充

2.5linewidth(lw): 直线宽度

对第一节案例添加直线属性:虚线表示,坐标用绿色左半填充圈标记

#

直线属性
plt.plot(x_data,y_view,linestyle="--"
,marker="o",markeredgecolor="g",fillstyle="left")

更多属性:
在matplotlib官网对直线2D属性有更多的介绍

 

3. 坐标管理

3.1坐标轴名字设置

  • 设置X轴名称:pyplot.xlabel(str)
  • 设置y轴名称:pyplot.ylabel(str)

3.2坐标轴刻度设置

  • x轴坐标刻度设置:pyplot.xticks(ticks=[],rotation)
  • y轴坐标刻度设置:pyplot.yticks(ticks=[],rotation)

参数说明:

  • ticks:列表类型,表示x轴范围
  • rotation:翻转角度

3.3坐标轴位置设置

  • 坐标轴位置设置需要通过pyplot.gca()先获取当前的Axes
  • 然后调用ax.spines[].set_position()设置位置
  • ax.spines['bottom'].set_position(('axes',0.5)) 表示将x轴设置在y轴50%处

3.4指定坐标值标注

pyplot.annotate() 展示指定坐标点的(x,y)值

用接口参数说明:

 

参数 说明
txt 展示的文本
xy 注释的(x,y)
xytext xy展示的文本
color 展示的文本颜色

继续改造第一节案例:标记出最大访问,y轴移到x轴中心

max_id = np.argmax(y_view)


show_max = '['+str(x_data[max_id])+','+str(y_view[max_id])+']'


plt.figure(figsize=(20,5),dpi=90)

ax= plt.gca()

ax.spines["left"].set_position(('axes',0.5))

plt.plot(x_data,y_view,linestyle="--",marker="o",markeredgecolor="g",fillstyle="left")

plt.xticks(ticks=np.arange(0,30),rotation=60)

plt.annotate(show_max, xy=(x_data[max_id],y_view[max_id] ), xytext=(x_data[max_id],y_view[max_id]), color='r')

 

4. 多条折线展示图

在一个图表中,我们可以多次调用plot()绘制多条折线展示在同一个表格中

```python
star_view = [random.randint(100,200) for i in range(30)]

plt.plot(x_data,y_view,linestyle="--",marker="o",markeredgecolor="g",fillstyle="left")
plt.plot(x_data,star_view,linestyle="-",marker="s",markeredgecolor="r",fillstyle="right")
```
 

 

5. 图列管理

当一个图表中存在多个折线图时,我们需要使用图例管理来对每个折线代表对象

  1. pyplot.legend(loc): 对图表中折线进行说明
  2. loc参数属性值:

 

属性 代码 属性 代码
'best' 0 'right' 5
'upper right' 1 'center left' 6
'upper left' 2 'center right' 7
'lower left' 3 'lower center' 8
'lower right' 4 'upper center' 9
'center' 10

label属性,注释每条折线的对象

plt.plot(x_data,y_view,linestyle="--",marker="o",markeredgecolor="g",fillstyle="left",label="all")
plt.plot(x_data,star_view,linestyle="-",marker="s",markeredgecolor="r",fillstyle="right",label="star")

plt.legend()

 

总结:
本文 我们对matplotlib 模块 折线图plot()相关方法和属性进行,大家在平时工作中可以多多实践,折线图还是用的比较多的

关于python 用matplotlib绘制折线图详情的文章就介绍至此,更多相关python matplotlib绘制折线图内容请搜索编程宝库以前的文章,希望以后支持编程宝库

 一、保留两位小数 且 做四舍五入处理四舍六入五成双, 四舍六入五凑偶的意思, 根据百度词条的解释如下:(1)当精确位后面一位的数字是1-4的时候,舍去(2)当精确位后面一位的数字是6-9的时候, ...