Python图表库Matplotlib 组成部分介绍
图表有很多个组成部分,例如标题、x/y轴名称、大刻度小刻度、线条、数据点、注释说明等等。
我们来看官方给的图,图中标出了各个部分的英文名称

Matplotlib提供了很多api,开发者可根据需求定制图表的样式。
前面我们设置了标题和x/y轴的名称,本文介绍更多设置其他部分的方法。
绘图
先绘制一个事例图。然后以此为基础进行定制。
def demo2():
x_list = []
y_list = []
for i in range(0, 365):
x_list.append(i)
y_list.append(math.sin(i * 0.1))
ax = plt.gca()
ax.set_title('rustfisher.com mapplotlib example')
ax.set_xlabel('x')
ax.set_ylabel('y = sin(x)')
ax.grid()
plt.plot(x_list, y_list)
plt.show()
if __name__ == '__main__':
print('rustfisher 图表讲解')
demo2()
运行得到
.png)
红色框框里的是figure;绿色框框里的叫做ax。
代码中ax = plt.gca()获取到的就是绿色框框里的部分(对象)。
Figure 大图
Figure代表整张图,暂时称为“全图”或者“大图”。一张图里可以有多个子图表。最少必须要有一个图表。像上面那样。
Axes 数据图
一张张的图,图里显示着数据,暂称为“数据图”。一个大图里可以有多个数据图。但单个数据图对象只能在1个大图里。
多张数据图 subplots
例如同时存在2个数据图
.png)
def demo_subplot():
x_list = []
y_list = []
y2_list = []
for i in range(0, 365):
x_list.append(i)
y_list.append(math.sin(i * 0.1))
y2_list.append(math.cos(i * 0.1))
fig, (ax1, ax2) = plt.subplots(2)
ax1.set_title('rustfisher.com 1')
ax2.set_title('rustfisher.com 2')
ax1.set_xlabel('x')
ax1.set_ylabel('y = sin(x)')
ax2.set_xlabel('x')
ax2.set_ylabel('y = cos(x)')
ax1.plot(x_list, y_list)
ax2.plot(x_list, y2_list)
plt.show()
调用subplots()接口,传入数字指定要多少张数据图。
返回的多张图要用括号括起来。每个数据图可以绘制(plot)不同的数据。
标题用set_title()来设置。
可以看到上下两张图太挤了,有重叠部分。可以在plt.show()之前加一个fig.tight_layout()让它们拉开一点距离。
.png)
坐标轴
对于2维数据图,它有2个坐标,横坐标和纵坐标。有一些接口可以设置参数。
例如控制坐标轴的名字set_xlabel() set_ylabel;
显示数据范围
set_xlim方法可以控制x轴数据显示范围。同理y轴用set_ylim来控制。
对于显示范围,set_xlim方法主要参数为left和right;或者用xmin xmax。这两套不能同时使用。
set_ylim主要参数是top bottom;或者ymin ymax。这两套不能同时使用。
增加显示范围控制的代码
def demo3():
x_list = []
y_list = []
y2_list = []
for i in range(0, 365):
x_list.append(i)
y_list.append(math.sin(i * 0.1))
y2_list.append(math.cos(i * 0.1))
fig, (ax1, ax2) = plt.subplots(2)
ax1.set_title('rustfisher.com 1')
ax1.set_xlabel('x')
ax1.set_ylabel('y = sin(x)')
ax2.set_title('rustfisher.com 2')
ax2.set_xlabel('x')
ax2.set_ylabel('y = cos(x)')
ax1.set_xlim(left=50, right=200.6) # 控制x轴显示范围
ax1.set_ylim(top=1, bottom=0.3) # 控制y轴显示范围
ax2.set_xlim(xmin=1, xmax=156.6) # 控制x轴显示范围
ax2.set_ylim(ymin=-0.3, ymax=0.3) # 控制y轴显示范围
ax1.plot(x_list, y_list)
ax2.plot(x_list, y2_list)
fig.tight_layout()
plt.show()
运行结果
.png)
刻度
tick意思是标记。在坐标轴上的是刻度。Major tick暂称为大刻度,minor tick暂称为小刻度。
使用set_xticks方法控制刻度显示。传入的列表是我们希望显示的刻度。
minor参数默认为False,不显示小刻度。
关键代码如下
ax1.set_xticks([50, 60, 70, 150])
ax1.set_yticks([0.1, 0.2, 0.3, 0.7, 0.9])
ax1.grid() # 显示格子
ax2.set_xticks([1, 60, 70, 150], minor=True)
ax2.set_yticks([-0.1, 0, 0.1, 0.3], minor=True)
ax2.grid()

可见当minor=True,传入的刻度列表有可能不显示。
也可以控制大刻度上的文字旋转
plt.setp(ax1.xaxis.get_majorticklabels(), rotation=-45)
plt.setp(ax2.xaxis.get_majorticklabels(), rotation=-60)

边线 spine
spine是脊柱的意思,这里我们先称为边线。有上下左右4条边线。名称是top bottom left right
可以直接从图表对象获取它的边线,比如右边线ax1.spines.right。
一些简单的操作,例如
set_visible显示和隐藏set_ticks_position刻度显示的位置set_bounds边线显示范围set_linewidth线的宽度
隐藏右边线和上边线
ax1.spines.right.set_visible(False)
ax1.spines.top.set_visible(False)
让刻度显示在右边和上方
ax2.yaxis.set_ticks_position('right')
ax2.xaxis.set_ticks_position('top')
设置边线显示范围
ax3.spines.left.set_bounds(-0.5, 0.5)
ax3.spines.top.set_bounds(340, 400)
设置线的宽度
ax3.spines.bottom.set_linewidth(2)
完整代码如下
import math
import matplotlib.pyplot as plt
def demo_spine():
x_list = []
y_list = []
for i in range(0, 365):
x_list.append(i)
y_list.append(math.sin(i * 0.1))
fig, (ax1, ax2, ax3) = plt.subplots(3)
ax_list = [ax1, ax2, ax3]
for i in range(0, 3):
cur_ax = ax_list[i]
cur_ax.set_title('rustfisher.com ' + str(i))
cur_ax.plot(x_list, y_list)
cur_ax.set_xlabel('x')
cur_ax.set_ylabel('y = sin(x)')
ax1.spines.right.set_visible(False)
ax1.spines.top.set_visible(False)
ax2.spines.bottom.set_visible(False)
ax2.spines.left.set_visible(False)
ax2.yaxis.set_ticks_position('right')
ax2.xaxis.set_ticks_position('top')
ax3.spines.left.set_bounds(-0.5, 0.5)
ax3.spines.top.set_bounds(340, 400)
ax3.spines.bottom.set_linewidth(2)
fig.tight_layout()
plt.show()
运行截图

数据点
控制数据点的样式。下面我们在一张图表里绘制多条数据线。
def demo_line():
x_list = []
y_list = []
y2_list = []
y3_list = []
for i in range(0, 20):
x_list.append(i)
y_list.append(math.sin(i) * 2 - 4)
y2_list.append(math.sin(i) * 2)
y3_list.append(math.cos(i) * 1.3 + 3)
plt.plot(x_list, y_list, color='blue', linestyle='-.', linewidth=2, markersize=4)
plt.plot(x_list, y2_list, 'go', linewidth=1)
plt.plot(x_list, y3_list, 'r+')
plt.show()
plot()方法中,支持多种选项。
linestyle支持的选项
'-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'

注释 legend
添加注释,调用lengend()方法。
在前面代码基础上添加
plt.plot(x_list, y_list, color='blue', linestyle='-.', linewidth=2, markersize=4)
plt.plot(x_list, y2_list, 'go', linewidth=1)
plt.plot(x_list, y3_list, 'r+')
plt.legend(['math.sin(i) * 2 - 4', 'math.sin(i) * 2', 'math.cos(i) * 1.3 + 3'])

控制注释显示的地方,添加bbox_to_anchor和bbox_transform属性
plt.legend(['math.sin(i) * 2 - 4', 'math.sin(i) * 2', 'math.cos(i) * 1.3 + 3'], bbox_to_anchor=(1, 1),
bbox_transform=plt.gcf().transFigure)

中文乱码问题
在设置标题用到中文的时候,可能会出现乱码。
可以设置rcParams的字体,解决乱码问题。
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
至此,我们把图表中各个部分都简要介绍了一下。
参考
本例环境
- macOS
- PyCharm CE
- Python3
参考资料
- 【运营的Python指南】绘制图表Matplotlib快速入门
- Python笔记 https://rustfisher.com/categories/Python/
- matplotlib https://matplotlib.org/
Python图表库Matplotlib 组成部分介绍的更多相关文章
- python标准库之glob介绍
python标准库之glob介绍 glob 文件名模式匹配,不用遍历整个目录判断每个文件是不是符合. 1.通配符 星号(*)匹配零个或多个字符 import glob for name in glob ...
- Python第三方库matplotlib(2D绘图库)入门与进阶
Matplotlib 一 简介: 二 相关文档: 三 入门与进阶案例 1- 简单图形绘制 2- figure的简单使用 3- 设置坐标轴 4- 设置legend图例 5- 添加注解和绘制点以及在图形上 ...
- Python可视化库-Matplotlib使用总结
在做完数据分析后,有时候需要将分析结果一目了然地展示出来,此时便离不开Python可视化工具,Matplotlib是Python中的一个2D绘图工具,是另外一个绘图工具seaborn的基础包 先总结下 ...
- python第三方库requests简单介绍
一.发送请求与传递参数 简单demo: import requests r = requests.get(url='http://www.itwhy.org') # 最基本的GET请求 print(r ...
- Python标准库:1. 介绍
标准库包括了几种不同类型的库. 首先是那些核心语言的数据类型库,比方数字和列表相关的库.在核心语言手冊里仅仅是描写叙述数字和列表的编写方式,以及它的排列,而未定义它的语义. 换一句话说,核心语言手冊仅 ...
- Python可视化库Matplotlib的使用
一.导入数据 import pandas as pd unrate = pd.read_csv('unrate.csv') unrate['DATE'] = pd.to_datetime(unrate ...
- python可视化库 Matplotlib 01 figure的详细用法
1.上一章绘制一幅最简单的图像,这一章介绍figure的详细用法,figure用于生成图像窗口的方法,并可以设置一些参数 2.先看此次生成的图像: 3.代码(代码中有详细的注释) # -*- enco ...
- Python图表绘制Matplotlib
引入 import numpy as npimport pandas as pdimport matplotlib.pyplot as plt# 导入相关模块 使用 # 图表窗口1 → plt.sho ...
- Python NLP库top6的介绍和比较
文章来源:ActiveWizards https://medium.com/activewizards-machine-learning-company/comparison-of-top-6-pyt ...
随机推荐
- 激光雷达Lidar Architecture and Lidar Design(上)
激光雷达Lidar Architecture and Lidar Design(上) 介绍 激光雷达结构: 基本条件 构型和基本布置 激光雷达设计: 基本思想和基本原则 总结 介绍 激光雷达结构是激光 ...
- ST为飞行时间传感器增加了多目标测距
ST为飞行时间传感器增加了多目标测距 ST adds multi-object ranging to time-of-flight sensors STMicroelectronics已经扩展了其Fl ...
- Postman之newman的安装
一.newman简介:newman是为Postman而生,专门用来运行Postman编写好的脚本:使用newman,你可以很方便的用命令行来执行postman collections. 二.newma ...
- 【NX二次开发】打开信息窗口UF_UI_open_listing_window
头文件:uf_ui_ugopen.h函数名:UF_UI_open_listing_window 函数说明:打开信息窗口 测试代码: #include <uf.h> #include < ...
- SpringCloud(1)生态与简绍
一:微服务架构简绍学习目标 1.技术架构的演变,怎么一步步到微服务的:2.什么是微服务,优点与缺点 :3.SOA(面向服务)与MicroServices(微服务)的区别 :4.Dubbo 与Spri ...
- 不下软件,照样可以完美正确格式化树莓派SD卡!(恢复U盘/SD卡到满容量)
树莓派作用千千万,系统崩溃的理由也数不胜数(不要问我为啥知道),所以系统的重装和sd卡的格式化也在所难免.顺便给大家看一下我今天的成果,我不就是不小心摔了一下我的树莓派...我和sd卡一定是冤家! 捡 ...
- NOIP模拟测试5「星际旅行·砍树·超级树」
星际旅行 0分 瞬间爆炸. 考试的时候觉得这个题怎么这么难, 打个dp,可以被儿子贡献,可以被父亲贡献,还有自环,叶子节点连边可以贡献,非叶子也可以贡献,自环可以跑一回,自环可以跑两回, 关键是同一子 ...
- 通过ffmpeg转换为mp4格式
FFMPEG -i example.wmv -c:v libx264 -strict -2 output.mp4FFMPEG -i example.wmv -c:v libx264 -stri ...
- Unity获取系统时间
示例如下: Debug.Log(System.DateTime.Now); // 当前本地时间 (年月日时分秒) -- 10/4/2018 9:38:19 PM Debug.Log(System.Da ...
- MySQL数据库性能优化与监控实战(阶段四)
MySQL数据库性能优化与监控实战(阶段四) 作者 刘畅 时间 2020-10-20 目录 1 sys数据库 1 2 系统变量 1 3 性能优化 1 3.1 硬件层 1 3.2 系统层 1 3.3 软 ...