上海做网站的公司电话,河北wap网站建设,wordpress后台排版全部乱,国家工信部网站域名查询系统Matplotlib简易使用教程0.matplotlib的安装1.导入相关库2.画布初始化2.1 隐式创建2.2 显示创建2.3 设置画布大小2.4 plt.figure()常用参数3.plt. 能够绘制图像类型3.1等高线3.2 箭头arrow4.简单绘制小demodemo1.曲线图demo2-柱状、饼状、曲线子图5.plt.plot()--设置曲线颜色,粗…
Matplotlib简易使用教程0.matplotlib的安装1.导入相关库2.画布初始化2.1 隐式创建2.2 显示创建2.3 设置画布大小2.4 plt.figure()常用参数3.plt. 能够绘制图像类型3.1等高线3.2 箭头arrow4.简单绘制小demodemo1.曲线图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.colorbar9.错误信息9.1 RuntimeError: Invalid DISPLAY variable10.Seaborn11.BokehMatplotlib 是 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(numNone, figsizeNone, dpiNone, facecolorNone, edgecolorNone, frameonTrue, FigureClassclass ‘matplotlib.figure.Figure’, clearFalse, **kwargs 0.num–a unique identifier for the figure (int or str) 1.figsize–画布大小(default: [6.4, 4.8] in inches.) 2.dpiNone–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.FigureClassclass ‘matplotlib.figure.Figure’, 7.clearFalse, 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.在等高线图中增加labelplt.clabel() 5.矩阵热图plt.imshow() 6.在随机矩阵图中增加colorbarplt.colorbar() 7.直方图 plt.hist( data,bin) https://www.jianshu.com/p/f2f75754d4b3
隐式创建时用plt.plot()在默认坐标系中添加数据显示创建时用axes1.plot()在对应的坐标系中添加绘制数据 .plot()用于绘制曲线图
3.1等高线
import matplotlib.pyplot as plt
n256
xnp.linspace(-3,3,n)
ynp.linspace(-3,3,n)
X,Ynp.meshgrid(x,y) #把XY转换成网格数组,X.shapenn,Y.shapenn
plt.contourf(X,Y,height(X,Y),8,alpha0.75,cmapplt.cm.hot)
#8:8210,将高分为10部分
#alpha透明度
#cmapcolor map
#use plt.contour to add contour lines
Cplt.contour(X,Y,height(X,Y),8,colors“black”,linewidth.5)
#adding label
plt.clabel(C,inlineTrue,fontsize10)
#clabel:cycle的labelinlineTrue表示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, width0.1, length_includes_headTrue, head_width1,head_length3, fcb,ecb)参考文档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, edgecolorwhite)
plt.bar(X, -Y2, facecolor#ff9999, edgecolorwhite)# 利用plt.text 指定文字出现的坐标和内容
for x, y in zip(X,Y1):plt.text(x0.4, y0.05, %.2f % y, hacenter, vabottom)
# 限制坐标轴的范围
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, endpointTrue)
Y_C, Y_S np.cos(X), np.sin(X)plt.plot(X, Y_C, colorblue, linewidth2.5, linestyle-)
plt.plot(X, Y_S, colorred, linewidth2.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”,linewidth2,linestyle’:’,label‘Jay income’, marker‘o’) 参数含义 0–xy :array 表示 x 轴与 y 轴对应的数据 1–color :string 表示折线的颜色 None 2–label :string 数据图例内容label‘实际数据’ None配合plt.legend()使用 3–linestyle :string 表示折线的类型 4–marker :string 表示折线上数据点处的类型 None 5–linewidth :数值 线条粗细linewidth1.5.0.3 1 6–alpha :0~1之间的小数 表示点的透明度 None
注label:配合 plt.legend()使用legend(…, fontsize20)可以设置图例的字号大小 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, fontdictNone, withdashFalse, **kwargs) 可以用来给线上的sian打标签/标注
x y:scalars 放置text的位置途中的横纵坐标位置s:str 要写的内容textfontdict: dictionary, optional, default: None 一个定义s格式的dictwithdash: boolean, optional, default: False。如果True则创建一个 TextWithDash实例。color控制文字颜色
借助 transformax.transAxestext 标注在子图相对位置
# 设置文本目标位置 左上角距离 Y 轴 0.01 倍距离距离 X 轴 0.95倍距离
ax.text(0.01, 0.95, test string, transformax.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, dpiNone, facecolor’w’, edgecolor’w’, orientation’portrait’, papertypeNone, formatNone, transparentFalse, bbox_inchesNone, pad_inches0.1, frameonNone) 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’,fontsize12,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**2np.random.randn(*train_x.shape)*0.3
p1 plt.scatter(train_x, train_y_1, cred, markerv )
p2 plt.scatter(train_x, train_y_2, cblue, markero )
legend plt.legend([p1, p2], [CH, US], facecolorblue)# 省略[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(normnorm, cmapcmp axax) # 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的backendAgg、Cairo、PS、PDF和SVG。 import matplotlib.pyplot as plt plt.switch_backend(‘agg’) 10.Seaborn
Seaborn是一种基于matplotlib的图形可视化python libraty。它提供了一种高度交互式界面便于用户能够做出各种有吸引力的统计图表。
参考资料 https://baijiahao.baidu.com/s?id1659039367066798557wfrspiderforpc https://www.kesci.com/home/column/5b87a78131902f000f668549 https://blog.csdn.net/gdkyxy2013/article/details/79585922
11.Bokeh
针对浏览器中图形演示的交互式绘图工具。目标是使用d3.js样式(不懂)提供的优雅简洁新颖的图形风格同时提供大型数据集的高性能交互功能。
他提供的交互式电影检索工具蛮吸引我的吼并打不开这个网址。 http://demo.bokehplots.com/apps/movies Python学习笔记4——Matplotlib中的annotate注解的用法 matplotlib xticks用法 matplotlib.pyplot 标记出曲线上最大点和最小点的位置 matplotlib 中子图subplot 绘图时标题重叠解决办法备忘