06-03 Matplotlib
2021-10-28 15:05:41 1 举报
AI智能生成
Matplotlib知识脉络,持续更新
作者其他创作
大纲/内容
入门
参考资料
图表展示规则 Ten Simple Rules for Better Figures
Matplotlib入门详细教程
Matlpotlib API概览官方文档
格拉斯哥 Programming and System Development - Data Visualization
安装
conda install matplotlib
导入
import matplotlib.pyplot as plt
jupyter
%matplotlib inline
基本概念
一开始的plt默认就有一个figure和axis,直接就可以画
更加复杂的面向对象方法需要在figure上创建axis坐标轴然后再画图
先使用plt.figure创建画布,然后使用add_**函数创建坐标轴
面向对象方式
axes
参考文档
matplotlib.axes<br>
面向对象figure作图法
add_subplot()
实例
import numpy as np <br>import matplotlib.pyplot as plt <br>x = np.arange(0, 100) <br>#新建figure对象<br>fig=plt.figure()<br>#新建子图1<br>ax1=fig.add_subplot(2,2,1) <br>ax1.plot(x, x) <br>#新建子图3<br>ax3=fig.add_subplot(2,2,3)<br>ax3.plot(x, x ** 2)<br>ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)<br>#新建子图4<br>ax4=fig.add_subplot(2,2,4)<br>ax4.plot(x, np.log(x)) <br>plt.show()<br>
add_axes()
实例
import matplotlib.pyplot as plt <br><br>#新建figure<br>fig = plt.figure()<br># 定义数据<br><br>x = [1, 2, 3, 4, 5, 6, 7]<br>y = [1, 3, 4, 2, 5, 8, 6]<br>#新建区域ax1<br><br>#figure的百分比,从figure 10%的位置开始绘制, 宽高是figure的80%<br>left, bottom, width, height = 0.1, 0.1, 0.8, 0.8<br># 获得绘制的句柄<br>ax1 = fig.add_axes([left, bottom, width, height])<br>ax1.plot(x, y, 'r')<br>ax1.set_title('area1')<br><br>#新增区域ax2,嵌套在ax1内<br>left, bottom, width, height = 0.2, 0.6, 0.25, 0.25<br># 获得绘制的句柄<br>ax2 = fig.add_axes([left, bottom, width, height])<br>ax2.plot(x,y, 'b')<br>ax2.set_title('area2')<br>plt.show()<br>
绘制图表
热度图<br>(heatmap)
colorbar
散点图<br>scatter
格式
ax.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, <br>vmax=None, alpha=None, linewidths=None, *, edgecolors=None, <br>plotnonfinite=False, data=None, **kwargs)[source]
折线图<br>plot
配置图例
标题
title
axes.set_title()
图例显示位置
legend
网格
grid
添加文字
text
格式
添加箭头
arrow
添加标记
annotate
参考资料
Matplotlib中annotate的简单用法
格式
ax.annotate(text, xy, *args, **kwargs)[source]
参数
xy
(float, float)
坐标轴
坐标轴标题
xlabel/ylabel
axes.set_xlabel()
坐标轴范围
axis/xlim/ylim
axis接受4个参数分别作为x和y轴的范围参数
axes.set_xlim()
坐标轴位置
x坐标轴
axes.xaxis.tick_top()
axes.xaxis.tick_bottom()
y坐标轴
axes.yaxis.tick_right()
axes.yaxis.tick_left()
坐标轴是否显示
是否显示坐标轴的长方形框框
axes.set_frame_on(b=True)
坐标轴刻度范围
xticks/yticks
axes.set_xticks()
坐标轴刻度显示
xticklabels/yticklabels
axes.set_xticklabels()
Matlab方式
pylpot
参考文档
matplotlib.pyplot
创建画板
subplot
实例
import numpy as np <br>import matplotlib.pyplot as plt <br>x = np.arange(0, 100) <br>#作图1<br>plt.subplot(221) <br>plt.plot(x, x) <br>#作图2<br>plt.subplot(222) <br>plt.plot(x, -x) <br> #作图3<br>plt.subplot(223) <br>plt.plot(x, x ** 2) <br>plt.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)<br>#作图4<br>plt.subplot(224) <br>plt.plot(x, np.log(x)) <br>plt.show() <br>
subplots
实例
import numpy as np <br>import matplotlib.pyplot as plt<br>x = np.arange(0, 100) <br>#划分子图<br>fig,axes=plt.subplots(2,2)<br>ax1=axes[0,0]<br>ax2=axes[0,1]<br>ax3=axes[1,0]<br>ax4=axes[1,1]<br>#作图1<br>ax1.plot(x, x) <br>#作图2<br>ax2.plot(x, -x)<br> #作图3<br>ax3.plot(x, x ** 2)<br>ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)<br>#作图4<br>ax4.plot(x, np.log(x)) <br>plt.show() <br>
axes
解释
位置更加自由,接收
格式
plt.axes([left,bottom,width,height])
实例
import matplotlib.pyplot as plt<br>import numpy as np<br># 创建数据<br>dt = 0.001<br>t = np.arange(0.0, 10.0, dt)<br>r = np.exp(-t[:1000]/0.05) # impulse response<br>x = np.random.randn(len(t))<br>s = np.convolve(x, r)[:len(x)]*dt # colored noise<br># 默认主轴图axes是subplot(111)<br>plt.plot(t, s)<br>plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)])<br>plt.xlabel('time (s)')<br>plt.ylabel('current (nA)')<br>plt.title('Gaussian colored noise')<br>#内嵌图<br>plt.axes([.65, .6, .2, .2], facecolor='y')<br>n, bins, patches = plt.hist(s, 400)<br>plt.title('Probability')<br>plt.xticks([])<br>plt.yticks([])<br>#另外一个内嵌图<br>plt.axes([0.2, 0.6, .2, .2], facecolor='y')<br>plt.plot(t[:len(r)], r)<br>plt.title('Impulse response')<br>plt.xlim(0, 0.2)<br>plt.xticks([])<br>plt.yticks([])<br>plt.show()
绘制图表
折线图
plot
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
参数解析
fmt
格式
'[marker][line][color]'
Markers
'.' point marker<br>',' pixel marker<br>'o' circle marker<br>'v' triangle_down marker<br>'^' triangle_up marker<br>'<' triangle_left marker<br>'>' triangle_right marker<br>'1' tri_down marker<br>'2' tri_up marker<br>'3' tri_left marker<br>'4' tri_right marker<br>'8' octagon marker<br>'s' square marker<br>'p' pentagon marker<br>'P' plus (filled) marker<br>'*' star marker<br>'h' hexagon1 marker<br>'H' hexagon2 marker<br>'+' plus marker<br>'x' x marker<br>'X' x (filled) marker<br>'D' diamond marker<br>'d' thin_diamond marker<br>'|' vline marker<br>'_' hline marker
Line Styles
'-' solid line style<br>'--' dashed line style<br>'-.' dash-dot line style<br>':' dotted line style<br>
Colors
'b' blue<br>'g' green<br>'r' red<br>'c' cyan<br>'m' magenta<br>'y' yellow<br>'k' black<br>'w' white
**kwargs
linewidth
多组相同x坐标数组
x = [1, 2, 3]<br>y = np.array([[1, 2], [3, 4], [5, 6]])<br>plot(x, y)<br>
多组不同表现数据
plot(x1, y1, 'g^', x2, y2, 'g-')
使用Dict传递数据
使用data输入数据<br>x,y输入label坐标轴标题
plot('xlabel', 'ylabel', data=obj)
散点图
scatter
scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, <br>vmin=None, vmax=None, alpha=None, linewidths=None, *, <br>edgecolors=None, plotnonfinite=False, data=None, **kwargs)[source]
实例
参考资料
c
'b' blue<br>'g' green<br>'r' red<br>'c' cyan<br>'m' magenta<br>'y' yellow<br>'k' black<br>'w' white
marker
'.' point marker<br>',' pixel marker<br>'o' circle marker<br>'v' triangle_down marker<br>'^' triangle_up marker<br>'<' triangle_left marker<br>'>' triangle_right marker<br>'1' tri_down marker<br>'2' tri_up marker<br>'3' tri_left marker<br>'4' tri_right marker<br>'8' octagon marker<br>'s' square marker<br>'p' pentagon marker<br>'P' plus (filled) marker<br>'*' star marker<br>'h' hexagon1 marker<br>'H' hexagon2 marker<br>'+' plus marker<br>'x' x marker<br>'X' x (filled) marker<br>'D' diamond marker<br>'d' thin_diamond marker<br>'|' vline marker<br>'_' hline marker
条形图
bar/barh
bar(x, height, width=0.8, bottom=None, *,<br>align='center', data=None, **kwargs)[source]
直方图
hist
参考资料
实例
格式
hist(x, bins=None, range=None, density=False, weights=None, <br>cumulative=False, bottom=None, histtype='bar', align='mid', <br>orientation='vertical', rwidth=None, log=False, color=None,<br>label=None, stacked=False, *, data=None, **kwargs)[source]
参数
bins
将输入的x数据按多少个bin显示
饼图
pie
pie(x, explode=None, labels=None, colors=None, autopct=None,<br>pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0,<br>radius=1, counterclock=True, wedgeprops=None, textprops=None,<br>center=(0, 0), frame=False, rotatelabels=False, *, normalize=None, data=None)
实例
等高线图
countour
contour([X, Y,] Z, [levels], **kwargs)
实例
图像
imshow
配置图例
标题
title
格式
plt.title(label, ...)
参数
图例显示位置
legend
格式
plt.legend()
参数
默认
plt.legend()
使用画图函数定义时的label
loc
handles
传入画图函数的返回值,配合labels等确定顺序
labels
图例的说明
网格
grid
格式
plt.grid(b, which, axis, color, linestyle, linewidth, **kwargs)
参数
默认
plt.grid()
x,y轴都有
axis
取值为‘both’, ‘x’,‘y’。就是以什么轴为刻度生成网格。<br>例如我输入参数x就会在x轴方向上生成纵向的网格刻度。<br>没有输入的方向则不会显示网格刻度。
color
设置网格线的颜色。或者直接用c来代替color也可以
linestyle
可以用ls来代替linestyle, 设置网格线的风格,是连续实线,虚线或者其它不同的线条。 <br>| '-' | '--' | '-.' | ':' | 'None' | ' ' | '']
linewidth
网格线的宽度
添加文字
text
格式
plt.text(x, y, s, fontsize, verticalalignment,horizontalalignment,rotation , **kwargs)<br>
参数
x,y
表示标签添加的位置,默认是根据坐标轴的数据来度量的,是绝对值,<br>也就是说图中点所在位置的对应的值,特别的,<br>如果你要变换坐标系的话,要用到transform=ax.transAxes参数。
s
标签的符号,字符串格式,比如你想加个“我爱三行科创”,<br>更多的是你标注跟数据有关的主体,你如实写便是。
fontsize
加标签字体大小了,取整数
verticalalignment
垂直对齐方式 ,可选 ‘center’ ,‘top’ , ‘bottom’,‘baseline’
horizontalalignment
水平对齐方式 ,可以填 ‘center’ , ‘right’ ,‘left’ 等
rotation
标签的旋转角度,以逆时针计算,取整
添加箭头
arrow
添加标记
annotate
坐标轴
坐标轴标题
xlabel/ylabel
plt.xlabel()
坐标轴范围
axis/xlim/ylim
axis接受4个参数分别作为x和y轴的范围参数
plt.xlim()
坐标轴刻度范围
xticks/yticks
plt.xticks()
图片保存
plt.savefig(filename)
0 条评论
下一页