Matplotlib简易使用教程

  • 0.matplotlib的安装
  • 1.导入相关库
  • 2.画布初始化
    • 2.1 隐式创建
    • 2.2 显示创建
    • 2.3 设置画布大小
    • 2.4 plt.figure()常用参数
  • 3.plt. 能够绘制图像类型
    • 3.1等高线
    • 3.2 箭头arrow
  • 4.简单绘制小demo
    • demo1.曲线图
    • demo2-柱状、饼状、曲线子图
  • 5.plt.plot()--设置曲线颜色,粗细,线形,图例
  • 6.plt.xxx常用方法待更新
    • 6.1 plt.text() 图中添加文字
    • 6.2 plt.xlim() 设置坐标轴的范围
    • 6.3 plt.savefig()存图 参数详解
    • 6.4 xxx.title()设置标题
      • 6.4.1 极简设置
      • 6.4.2 plt.title()常用的参数
    • 6.5 plt.lengend()图例
    • 6.6 plt.xticks()改变坐标轴的刻度文字
  • 7. matplotlib.colorbar
  • 9.错误信息
    • 9.1 RuntimeError: Invalid DISPLAY variable
  • 10.Seaborn
  • 11.Bokeh

Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案。其子库pyplot包含大量与MatLab相似的函数调用接口。

matplotlib绘图三个核心概念–figure(画布)、axes(坐标系)、axis(坐标轴)

画图首先需要初始化(创建)一张画布,然后再创建不同的坐标系,在各自的坐标系内绘制相应的图线

绘图步骤

导入相关库->初始化画布->准备绘图数据->将数据添加到坐标系中->显示图像

注:可以绘制list,也可以绘制Numpy数组

0.matplotlib的安装

Linux 终端安装

pip install matplotlib

1.导入相关库

import numpy as np
import matplotlib.pyplot as plt

2.画布初始化

2.1 隐式创建

第一次调用plT.xxx(诸如:plt.plot(x,y))时,系统自动创建一个figure对象,并在figure上创建一个axes坐标系,基于此进行绘图操作(隐式初始化只能绘制一张图)

x=[1,2,5,7]
y=[4,9,6,8]
plt.plot(x,y)
plt.show()

2.2 显示创建

手动创建一个figure对象,在画布中添加坐标系axes

figure = plt.figure()
axes1 = figure.add_subplot(2,1,1)
Axes2= figure.add_subplot(2,1,2)

2.3 设置画布大小

figure = plt.figure(figsize=(xinch,yinch))

2.4 plt.figure()常用参数

画布属性(数量,大小)通过画布初始化方法设置,在初始化的时候填写响应的参数。

plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class ‘matplotlib.figure.Figure’>, clear=False, **kwargs

0.num–a unique identifier for the figure (int or str)
1.figsize–画布大小(default: [6.4, 4.8] in inches.)
2.dpi=None–The resolution of the figure in dots-per-inch.
3.facecolor–The background color
4.edgecolor–The border color
5.frameon–If False, suppress drawing the figure frame.
6.FigureClass=<class ‘matplotlib.figure.Figure’>,
7.clear=False, If True and the figure already exists, then it is cleared.

3.plt. 能够绘制图像类型

0.曲线图:plt.plot()
1.散点图:plt.scatter()
2.柱状图:plt.bar()
3.等高线图:plt.contourf()
4.在等高线图中增加label:plt.clabel()
5.矩阵热图:plt.imshow()
6.在随机矩阵图中增加colorbar:plt.colorbar()
7.直方图
plt.hist( data,bin)
https://www.jianshu.com/p/f2f75754d4b3

隐式创建时,用plt.plot()在默认坐标系中添加数据,显示创建时,用axes1.plot()在对应的坐标系中添加绘制数据 .plot()用于绘制曲线图

3.1等高线

import matplotlib.pyplot as plt
n=256
x=np.linspace(-3,3,n)
y=np.linspace(-3,3,n)
X,Y=np.meshgrid(x,y) #把X,Y转换成网格数组,X.shape=nn,Y.shape=nn
plt.contourf(X,Y,height(X,Y),8,alpha=0.75,cmap=plt.cm.hot)
#8:8+2=10,将高分为10部分,
#alpha:透明度
#cmap:color map
#use plt.contour to add contour lines
C=plt.contour(X,Y,height(X,Y),8,colors=“black”,linewidth=.5)
#adding label
plt.clabel(C,inline=True,fontsize=10)
#clabel:cycle的label,inline=True表示label在line内,fontsize表示label的字体大小
plt.show()

参考博文:https://cloud.tencent.com/developer/article/1544887

3.2 箭头arrow

 arrow_x1 = x_list[0]arrow_x2 = x_list[10]arrow_y1 = y_list[0]arrow_y2 = y_list[10]self.axis1.arrow(arrow_x1, arrow_y1, arrow_x2-arrow_x1, arrow_y2-arrow_y1, width=0.1, length_includes_head=True, head_width=1,head_length=3, fc='b',ec='b')

参考文档:matplotlib 画箭头的两种方式

4.简单绘制小demo

demo1.曲线图

import numpy as np
import matplotlib.pyplot as plt
figure = plt.figure()
axes1 = figure.add_subplot(2,1,1)  # 2*1 的 第2个图
axes2= figure.add_subplot(2,1,2)  # 2*1 的 第2个图
# axes1 = figure.add_subplot(2,2,1) 2*2 的 第1个图
x,y=[1,3,5,7],[4,9,6,8]
a,b=[1,2,4,5],[8,4,6,2]
axes1.plot(x,y)
Axes2.plor(a,b)plot.show() # 显示图像
path = "xxx/xxx/xxx.png"
plt.savefig(path) #保存图像
plt.close() # 关闭画布

demo2-柱状、饼状、曲线子图

# 20210406
import matplotlib.pylab as plt
import numpy as np# 1.柱状图
plt.subplot(2,1,1)
n = 12
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)plt.bar(X, +Y1, facecolor="#9999ff", edgecolor="white")
plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white")# 利用plt.text 指定文字出现的坐标和内容
for x, y in zip(X,Y1):plt.text(x+0.4, y+0.05, "%.2f" % y, ha="center", va="bottom")
# 限制坐标轴的范围
plt.ylim(-1.25, +1.25)# 2.饼状图
plt.subplot(2,2,3)
n = 20
Z = np.random.uniform(0, 1, n)
plt.pie(Z)# 3.第三部分
plt.subplot(2, 2, 4)
# 等差数列
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
Y_C, Y_S = np.cos(X), np.sin(X)plt.plot(X, Y_C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, Y_S, color="red", linewidth=2.5, linestyle="-")# plt.xlim-限定坐标轴的范围,plt.xticks-改变坐标轴上刻度的文字
plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$\pi$"])
plt.ylim(Y_C.min()*1.1, Y_C.max()*1.1)
plt.yticks([-1, 0, 1],[r"$-1$", r"$0$", r"$+1$"])
#plt.show()
plt.savefig("test.png")

5.plt.plot()–设置曲线颜色,粗细,线形,图例

plt.plot(x,y,color=“deeppink”,linewidth=2,linestyle=’:’,label=‘Jay income’, marker=‘o’)

参数含义:
0–x,y :array 表示 x 轴与 y 轴对应的数据
1–color :string 表示折线的颜色; None
2–label :string 数据图例内容:label=‘实际数据’ None,配合plt.legend()使用
3–linestyle :string 表示折线的类型;
4–marker :string 表示折线上数据点处的类型; None
5–linewidth :数值 线条粗细:linewidth=1.=5.=0.3 1
6–alpha :0~1之间的小数 表示点的透明度; None

注:label:配合 plt.legend()使用,legend(…, fontsize=20),可以设置图例的字号大小
https://www.cnblogs.com/shuaishuaidefeizhu/p/11361220.html

6.plt.xxx常用方法待更新

grid 背景网格
tick 刻度
axis label 坐标轴名称
tick label 刻度名称
major tick label 主刻度标签
line 线style 线条样式
marker 点标记
font 字体相关
annotate标注文字:https://blog.csdn.net/helunqu2017/article/details/78659490/

6.1 plt.text() 图中添加文字

plt.text(x, y, s, fontdict=None, withdash=False, **kwargs)

可以用来给线上的sian打标签/标注

x y :scalars 放置text的位置,途中的横纵坐标位置
s :str 要写的内容text
fontdict : dictionary, optional, default: None 一个定义s格式的dict
withdash : boolean, optional, default: False。如果True则创建一个 TextWithDash实例。
color 控制文字颜色

借助 transform=ax.transAxes,text 标注在子图相对位置

# 设置文本,目标位置 左上角,距离 Y 轴 0.01 倍距离,距离 X 轴 0.95倍距离
ax.text(0.01, 0.95, "test string", transform=ax.transAxes, fontdict={'size': '16', 'color': 'b'})

其他参数参考博文:https://blog.csdn.net/The_Time_Runner/article/details/89927708

6.2 plt.xlim() 设置坐标轴的范围

画布坐标轴设置

plt.xlim((-5, 5))
plt.ylim((0,80))

子图坐标轴配置

Axes.set_xlim((-5,5))
Axes.set_ylim((0,80))


问题1:横纵坐标等比例
plt.axis(“equal”)
Plt.axis(“scaled”) # 坐标值标的很小,曲线出描绘框架

6.3 plt.savefig()存图 参数详解

将绘制图像以png的形式存在当前文件夹下:

plt.savefig(“test.png”)

通过函数参数控制文件的存储格式,存储路径

savefig(fname, dpi=None, facecolor=’w’, edgecolor=’w’,
orientation=’portrait’, papertype=None, format=None,
transparent=False, bbox_inches=None, pad_inches=0.1,
frameon=None)

0–fname:A string containing a path to a filename, or a Python file-like object, or possibly some backend-dependent object such as PdfPages.(保存图片位置与路径的字符串)
1–dpi: None | scalar > 0 | ‘figure’
2–facecolor, edgecolor:(?)
3–orientation: ‘landscape’ | ‘portrait’
4–papertype:
5–format:(png, pdf, ps, eps and svg)
6–transparent:
7–frameon:
8–bbox_inches:
9–pad_inches:
10–bbox_extra_artists:

plt.show() 是以图片阻塞的方式显示图片,只有关掉显示窗口,代码才会继续运行。可以选择将图片保存下来(记得设置容易识别的文件名)查看,来保障程序运行的流畅性,

注:存完图关闭画布,防止内存占满

plt.close()

过多画布占内存报错

RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam figure.max_open_warning).
max_open_warning, RuntimeWarning)

6.4 xxx.title()设置标题

6.4.1 极简设置

1.隐式初始化(画布)图像标题设置

plt.title(‘Interesting Graph’,fontsize=‘large’)

2.显式初始化(子图/坐标系)图像标题设置

ax.set_title(‘title test’,fontsize=12,color=‘r’)

3.设置画布标题

figure.suptitle(“xxxx”)

6.4.2 plt.title()常用的参数

0.fontsize–设置字体大小,默认12,可选参数 [‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’,‘x-large’, ‘xx-large’]
1.fontweight–设置字体粗细,可选参数 [‘light’, ‘normal’, ‘medium’, ‘semibold’, ‘bold’, ‘heavy’, ‘black’]
2.fontstyle–设置字体类型,可选参数[ ‘normal’ | ‘italic’ | ‘oblique’ ],italic斜体,oblique倾斜
3.verticalalignment–设置水平对齐方式 ,可选参数 : ‘center’ , ‘top’ , ‘bottom’ ,‘baseline’
4.horizontalalignment–设置垂直对齐方式,可选参数:left,right,center
5.rotation–(旋转角度)可选参数为:vertical,horizontal 也可以为数字
6.alpha–透明度,参数值0至1之间
7.backgroundcolor–标题背景颜色
8.bbox–给标题增加外框 ,常用参数如下:
9.boxstyle–方框外形
10.facecolor–(简写fc)背景颜色
11.edgecolor–(简写ec)边框线条颜色
12.edgewidth–边框线条大小

参考链接–https://blog.csdn.net/helunqu2017/article/details/78659490/

6.5 plt.lengend()图例

from matplotlib import pyplot as plt
import numpy as nptrain_x = np.linspace(-1, 1, 100)
train_y_1 = 2*train_x + np.random.rand(*train_x.shape)*0.3
train_y_2 = train_x**2+np.random.randn(*train_x.shape)*0.3
p1 = plt.scatter(train_x, train_y_1, c='red', marker='v' )
p2= plt.scatter(train_x, train_y_2, c='blue', marker='o' )
legend = plt.legend([p1, p2], ["CH", "US"], facecolor='blue')# 省略[p1, p2] 直接写图例
plt.show()

6.6 plt.xticks()改变坐标轴的刻度文字

plt.xticks([-np.pi, -np.pi/2, np.pi/2, np.pi],[r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$\pi$"])

7. matplotlib.colorbar

plt.colorbar()
fig.colorbar(norm=norm, cmap=cmp ax=ax) # norm色卡数字范围,cmap 调制颜色

https://blog.csdn.net/sinat_32570141/article/details/105345725

9.错误信息

9.1 RuntimeError: Invalid DISPLAY variable

在远端服务器上运行时报错,本地运行并没有问题

原因:matplotlib的默认backend是TkAgg,而FltAgg、GTK、GTKCairo、TkAgg、Wx和WxAgg这几个backend都要求有GUI图形界面,所以在ssh操作的时候会报错。

解决:在导入matplotlib的时候指定不需要GUI的backend(Agg、Cairo、PS、PDF和SVG)。

import matplotlib.pyplot as plt
plt.switch_backend(‘agg’)

10.Seaborn

Seaborn是一种基于matplotlib的图形可视化python libraty。它提供了一种高度交互式界面,便于用户能够做出各种有吸引力的统计图表。

参考资料
https://baijiahao.baidu.com/s?id=1659039367066798557&wfr=spider&for=pc
https://www.kesci.com/home/column/5b87a78131902f000f668549
https://blog.csdn.net/gdkyxy2013/article/details/79585922

11.Bokeh

针对浏览器中图形演示的交互式绘图工具。目标是使用d3.js样式(不懂)提供的优雅,简洁新颖的图形风格,同时提供大型数据集的高性能交互功能。

他提供的交互式电影检索工具蛮吸引我的吼,并打不开这个网址,

python模块(5)-Matplotlib 简易使用教程相关推荐

  1. Python模块(8)-sklearn 简易使用教程

    sklearn 简易使用教程 1.scikit-learn的数据集 2.scikit-learn 的训练和预测 scikit-learn 是在Numpy,SciPy,Matplotlib三个模块上编写 ...

  2. Python模块(7)-SciPy 简易使用教程

    SciPy 简易使用教程 1. 符号计算 2. 函数向量化 3. 波形处理scipy.signal 3.1 滤波器 3.2 波峰定位 基于numpy的一个高级模块,为数学,物理,工程等方面的科学计算提 ...

  3. Python模块(1)-Argparse 简易使用教程

    argparse 简易使用教程 1基本函数 2例子程序演示 3常用参数解释 4argparse模块整理的缘起 1基本函数 argparse是Python中用于命令行中进行参数解析的一个模块,可以自动生 ...

  4. Python模块(2)-Numpy 简易使用教程

    Numpy模块 简易使用教程 1.数组创建 2.数组基本属性-维度.尺寸.数据类型 3.数组访问-索引.切片.迭代 4.数组的算术运算-加减乘除.转置求逆.极大极小 5.通用函数-sin,cos,ex ...

  5. python模块(6)-Pandas 简易使用教程

    Pandas 简易教程 1.Pandas简介 2.创建 2.1创建dataFrame 2.2创建Series 3.dataframe数据访问 3.1 获取一列--列标签 3.2 获取多列--列标签列表 ...

  6. Python模块(3)--PIL 简易使用教程

    PIL模块-用与记 1.图片导入Image.open() 2.图像显示.show() 4.查看图片属性.format,.size,.mode 3.图像格式转换.convert() 4.图像模式&quo ...

  7. 【Python模块】matplotlib 柱状图

    https://blog.csdn.net/denny2015/article/details/50581784 [搬运]python数字图像处理(9):直方图与均衡化 2.绘制直方图 绘图都可以调用 ...

  8. python模块之matplotlib.pyplot

    Matplotlib Matplotlib最早是为了可视化癫痫病人的脑皮层电图相关的信号而研发,因为在函数的设计上参考了MATLAB,所以叫做Matplotlib. Matplotlib是Python ...

  9. Python数据分析【1】:matplotlib库详细教程

    Python数据分析:matplotlib库详细教程 一.基本介绍 1. 数据分析 2. 环境安装 二.matplotlib 1. 基本介绍 2. 基本要点 3. 散点图/直方图/柱状图 4. 画图工 ...

最新文章

  1. php 对象json中文乱码,解决php json中文乱码问题
  2. js把文字中的空格替换为横线
  3. red hat关于桥接模式连不上外网或者没有IP
  4. java富文本编辑器KindEditor
  5. iframe内容 固定比例_允知研习|浅析固定总价合同的结算问题
  6. (WCF)wcf剖析阅读小计
  7. 深入浅出设计模式原则之里氏代换原则(Liskov Substitution Principle)
  8. 原生js、jQuery实现选项卡功能
  9. TensorFlow第五步:返回起点、深挖坑,解刨一个麻雀。
  10. java设计模式_备忘录模式
  11. Latex:使用latex双栏模板时,图片caption名称不显示
  12. matlab调取excel非线性拟合,用matlab实现非线性曲线拟合_matlab非线性曲线拟合
  13. 实例讲解反向传播(简单易懂)
  14. 迈开职场充电第一步,让我们在这个冬天邂逅社科院杜兰金融管理硕士项目
  15. 10个提升写作手法的方法
  16. 宝塔安装phalcon扩展及nginx配置
  17. XtraReport中改变文字方向
  18. python try: except: 捕获到的异常输出到 log文件
  19. 包围盒----碰撞检测
  20. 在OpenCV里实现二维离散卷积1

热门文章

  1. css 商城 两列_【云控基础】HTML+CSS基础入门
  2. 间歇性掉帧卡顿_电脑卡顿问题靠它解决,我只能帮你到这儿了
  3. 华为p50预装鸿蒙系统,华为P50系列将至,内部测试预装鸿蒙系统,还有4款重磅新品将发布...
  4. 神经网络与深度学习——TensorFlow2.0实战(笔记)(三)(python语句)
  5. 【转】医学图像中的窗宽、窗位!!
  6. SQL Server定时执行SQL语句
  7. ASP.Net请求处理机制初步探索之旅 - Part 2 核心
  8. 一步步编写操作系统 29 cpu缓存简介
  9. 设计模式(一)预备知识
  10. 【软件开发】制作个人移动式Git服务器