Python最常用的绘图库,提供了一整套十分适合交互式绘图的命令 API,比较方便的就可以将其嵌入到GUI应用程序中。
学习方式:从官网examples入门学习:
https://matplotlib.org/examples/index.html
https://matplotlib.org/gallery.html
1.Matplotlib 是一个非常强大的 Python 画图工具.。
2.手中有很多数据, 可是不知道该怎么呈现这些数据.,Matplotlib它能帮你画出美丽的: 线图; 散点图; 等高线图; 条形图; 柱状图; 3D 图形, 甚至是图形动画等等
基本使用
设置在jupyter中matplotlib的显示情况:
1.%matplotlib tk 在GUI中显示。
2.%matplotlib inline 在行内显示。
figure
figure:图形,matplotlib中的所有图像都是位于figure对象中,一个图像只能 有一个figure对象。matplotlib 的 figure 就是一个 单独的 figure 小窗口, 小窗口 里面还可以有更多的小图片.。
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams[\'font.sans-serif\'] = [\'SimHei\'] mpl.rcParams[\'axes.unicode_minus\'] = False data = np.arange(-3,3,0.1) x = np.sin(data) y = np.cos(data) # 画图 \'\'\' figsize:图形的大小 facecolor:边框的背景颜色 \'\'\' # plt.figure(frameon=False,facecolor=\'green\') # plt.plot(data,x,) # 第一个线图 # # plt.figure(figsize = (8,6)) # plt.plot(data,y) # 第二个线图 # # plt.figure(facecolor=\'red\') # plt.plot(data,x,) # 第三个线图第一条线 # plt.plot(data,y) # 第三个线图第二条线 plt.figure(facecolor=\'red\') plt.plot(data,x,data,y) # 不常见 plt.plot(x) # 如果只有一个参数这个参数 默认是Y轴的数据,X默认是从 0 - n # plt.axis(\'off\') plt.show()
颜色、标记和线型
plot(x,y,color=\'red\', linestyle=\'dashed\', marker=\'o\'.....)。
绘图中用到的直线属性包括:
(1)LineStyle:线形。
(2)LineWidth:线宽。
(3)Color:颜色。
(4)Marker:标记点的形状。
(5)label:用于图例的标签。
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams[\'font.sans-serif\'] = [\'SimHei\'] mpl.rcParams[\'axes.unicode_minus\'] = False data = np.arange(-3,3,0.1) x = np.sin(data) y = np.cos(data) plt.figure() # plt.plot(x,y,color = \'y\') # 设置颜色 # plt.plot(x,y,color = \'y\',linestyle = \'--\') # plt.plot(x,y,color = \'y\',linestyle = \'--\',linewidth = 5,marker = \'*\',markersize = 20) # plt.plot(x,y,color = \'y\',linestyle = \'--\',marker = \'o\',label = \'x-line\') plt.plot(x,y,\'*b--\',label = \'x-line\',markersize=20) # 简写方式 plt.legend(loc=\'lower right\') plt.axis(\'off\') plt.show()
线型:
\'\'\' \'-\' solid line style \'--\' dashed line style(线虚) \'-.\' dash-dot line style \':\' dotted line style(点虚) \'\'\'
market:
https://matplotlib.org/api/markers_api.html
\'\'\' \'.\' point marker \',\' pixel marker \'o\' circle marker \'v\' triangle_down marker \'^\' triangle_up marker \'<\' triangle_left marker \'>\' triangle_right marker \'1\' tri_down marker \'2\' tri_up marker \'3\' tri_left marker \'4\' tri_right marker \'s\' square marker \'p\' pentagon marker \'*\' star marker \'h\' hexagon1 marker \'H\' hexagon2 marker \'+\' plus marker \'x\' x marker \'D\' diamond marker \'d\' thin_diamond marker \'|\' vline marker \'_\' hline marker \'\'\'
颜色:
https://matplotlib.org/users/colormaps.html
https://matplotlib.org/examples/color/colormaps_reference.html
由其文档可知,在 colormap 类别上,有如下分类:
- perceptual uniform sequential colormaps:感知均匀的序列化 colormap
- sequential colormaps:序列化(连续化)色图 colormap;
- gray:0-255 级灰度,0:黑色,1:白色,黑底白字;
- gray_r:翻转 gray 的显示,如果 gray 将图像显示为黑底白字,gray_r 会将其显示为白底黑字;
- binary
- diverging colormaps:两端发散的色图 colormaps;
- seismic
- qualitative colormaps:量化(离散化)色图;
- miscellaneous colormaps:其他色图;
- rainbow
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams[\'font.sans-serif\'] = [\'SimHei\'] mpl.rcParams[\'axes.unicode_minus\'] = False dat = np.random.randint(0,255,(20,30)) dat2 = dat.reshape(-1) \'\'\'方法1\'\'\' # # 画图 # plt.scatter([i for i in range(600)],dat2,marker=\'.\',c=dat2,cmap=plt.get_cmap(\'gray_r\')) # # plt.scatter([i for i in range(600)],dat2,marker=\'.\',c=dat2, cmap=plt.cm.binary) #与\'gray_y\'一个效果。 # # plt.imshow(dat, cmap=plt.cm.binary) # plt.colorbar() # # plt.figure() # plt.scatter([i for i in range(600)],dat2,c=dat2,marker=\'.\', cmap=\'gray\') # plt.colorbar() \'\'\'方法2\'\'\' plt.figure() from matplotlib.colors import ListedColormap data = np.random.randint(1,5,(30,)) colors = (\'lightgreen\', \'cyan\', \'gray\', \'r\', \'b\') # cmp = ListedColormap(colors[:len(np.unique(data))]) cmp = ListedColormap(colors) plt.scatter([i for i in range(30)],data,marker=\'.\',c=data,cmap=cmp) plt.colorbar() # 展示图片 plt.show()
import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np \'\'\' (a)根据颜色名称(name)或者(Hex)生成 方法为cmap = mpl.colors.ListedColormap(clist),clist是包含有颜色名称或16进制码的列表,比如 \'\'\' cmap_list=[0]*3 cmap_list[0]=[\'r\',\'g\',\'b\',\'c\'] cmap_list[1]=[\'forestgreen\',\'springgreen\',\'yellowgreen\',\'lightsteelblue\',\'deepskyblue\'] cmap_list[2]=[\'#FAEBD7\',\'#00FFFF\',\'#FF7F50\',\'#006400\'] gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) fig, axes = plt.subplots(nrows=3) fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99) k=0 for ax, clist in zip(axes, cmap_list): cmap = mpl.colors.ListedColormap(clist) cmap.set_over(clist[0]) cmap.set_under(clist[-1]) ax.imshow(gradient, aspect=\'auto\', cmap=cmap) pos = list(ax.get_position().bounds) x_text = pos[0] - 0.01 y_text = pos[1] + pos[3]/2. fig.text(x_text, y_text, \'cmap_list_%d\'%(k+1), va=\'center\', ha=\'right\', fontsize=10) k=k+1 # Turn off *all* ticks & spines, not just the ones with colormaps. for ax in axes: ax.set_axis_off() plt.show() \'\'\' (b)根据RGB字典生成 字典的规律为R,G,B 或/和alpha四个元素,每个元素由3列n行。其中,R,G,B的第一列标记为x,第二列标记为y1,第三列标记为y2.用i来标记行。 在x[i]~x[i+1]之间,红(或绿,或蓝)对应的取值为y2[i]~y1[i+1].以下例, 0~0.25 :红色取值为0~0,绿色取值为0~0,蓝色取值为0.4~1; 0.25~0.5:红色取值为0~0.8,绿色取值为0~0.9,蓝色取值为1~1; 0.5~0.75:红色取值为1~1,绿色取值为0.9~0,蓝色取值为0.9~0; 0.75~1:红色取值为1~0.4,绿色取值为0~0,蓝色取值为0~0; 对于alpha,规则类似于R G B,如上例 0~0.5,透明度取值为1(不透明)~0.3 0.5~1,透明度取值为0.3~1(不透明) \'\'\' import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl cdict = {\'red\': ((0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.5, 0.8, 1.0), (0.75, 1.0, 1.0), (1.0, 0.4, 1.0)), \'green\': ((0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.5, 0.9, 0.9), (0.75, 0.0, 0.0), (1.0, 0.0, 0.0)), \'blue\': ((0.0, 0.0, 0.4), (0.25, 1.0, 1.0), (0.5, 1.0, 0.8), (0.75, 0.0, 0.0), (1.0, 0.0, 0.0)) } cdict1 = cdict.copy() \'\'\' Make a modified version of cdict with some transparency in the middle of the range.cdict1[\'alpha\'] = ((0.0, 1.0, 1.0), (0.25,1.0, 1.0), (0.5, 0.3, 0.3), (0.75,1.0, 1.0), (1.0, 1.0, 1.0)) \'\'\' cmap = mpl.colors.LinearSegmentedColormap(\'my_cmap\',cdict1) N = 1000 array_dg = np.random.uniform(0, 10, size=(N, 2)) colors = np.random.uniform(-2, 2, size=(N,)) plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=cmap) plt.colorbar() plt.show() \'\'\' 利用线性方法制作非线性分布色标 下列例子中,自定义函数make_colormap(seq)就可以实现这个功能,参数seq具体含义为 0.1以下为红色(这个可以随便改动,比如purple也可以) 0.1~0.3由红色线性过渡到白色 0.3~0.9由白色线性过渡到蓝色 0.9以上是蓝色 \'\'\' import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl def make_colormap(seq): """Return a LinearSegmentedColormap seq: a sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). """ seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {\'red\': [], \'green\': [], \'blue\': []} for i, item in enumerate(seq): if isinstance(item, float): r1, g1, b1 = seq[i - 1] r2, g2, b2 = seq[i + 1] cdict[\'red\'].append([item, r1, r2]) cdict[\'green\'].append([item, g1, g2]) cdict[\'blue\'].append([item, b1, b2]) return mpl.colors.LinearSegmentedColormap(\'CustomMap\', cdict) c = mpl.colors.ColorConverter().to_rgb rvb = make_colormap( [c(\'red\'),0.1,c(\'red\'), c(\'white\'), 0.33,c(\'white\'), c(\'green\'), 0.9, c(\'green\')]) print(rvb) N = 1000 array_dg = np.random.uniform(0, 10, size=(N, 2)) colors = np.random.uniform(-2, 2, size=(N,)) plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=rvb) plt.colorbar() plt.show()
\'\'\' cnames = { \'aliceblue\': \'#F0F8FF\', \'antiquewhite\': \'#FAEBD7\', \'aqua\': \'#00FFFF\', \'aquamarine\': \'#7FFFD4\', \'azure\': \'#F0FFFF\', \'beige\': \'#F5F5DC\', \'bisque\': \'#FFE4C4\', \'black\': \'#000000\', \'blanchedalmond\': \'#FFEBCD\', \'blue\': \'#0000FF\', \'blueviolet\': \'#8A2BE2\', \'brown\': \'#A52A2A\', \'burlywood\': \'#DEB887\', \'cadetblue\': \'#5F9EA0\', \'chartreuse\': \'#7FFF00\', \'chocolate\': \'#D2691E\', \'coral\': \'#FF7F50\', \'cornflowerblue\': \'#6495ED\', \'cornsilk\': \'#FFF8DC\', \'crimson\': \'#DC143C\', \'cyan\': \'#00FFFF\', \'darkblue\': \'#00008B\', \'darkcyan\': \'#008B8B\', \'darkgoldenrod\': \'#B8860B\', \'darkgray\': \'#A9A9A9\', \'darkgreen\': \'#006400\', \'darkkhaki\': \'#BDB76B\', \'darkmagenta\': \'#8B008B\', \'darkolivegreen\': \'#556B2F\', \'darkorange\': \'#FF8C00\', \'darkorchid\': \'#9932CC\', \'darkred\': \'#8B0000\', \'darksalmon\': \'#E9967A\', \'darkseagreen\': \'#8FBC8F\', \'darkslateblue\': \'#483D8B\', \'darkslategray\': \'#2F4F4F\', \'darkturquoise\': \'#00CED1\', \'darkviolet\': \'#9400D3\', \'deeppink\': \'#FF1493\', \'deepskyblue\': \'#00BFFF\', \'dimgray\': \'#696969\', \'dodgerblue\': \'#1E90FF\', \'firebrick\': \'#B22222\', \'floralwhite\': \'#FFFAF0\', \'forestgreen\': \'#228B22\', \'fuchsia\': \'#FF00FF\', \'gainsboro\': \'#DCDCDC\', \'ghostwhite\': \'#F8F8FF\', \'gold\': \'#FFD700\', \'goldenrod\': \'#DAA520\', \'gray\': \'#808080\', \'green\': \'#008000\', \'greenyellow\': \'#ADFF2F\', \'honeydew\': \'#F0FFF0\', \'hotpink\': \'#FF69B4\', \'indianred\': \'#CD5C5C\', \'indigo\': \'#4B0082\', \'ivory\': \'#FFFFF0\', \'khaki\': \'#F0E68C\', \'lavender\': \'#E6E6FA\', \'lavenderblush\': \'#FFF0F5\', \'lawngreen\': \'#7CFC00\', \'lemonchiffon\': \'#FFFACD\', \'lightblue\': \'#ADD8E6\', \'lightcoral\': \'#F08080\', \'lightcyan\': \'#E0FFFF\', \'lightgoldenrodyellow\': \'#FAFAD2\', \'lightgreen\': \'#90EE90\', \'lightgray\': \'#D3D3D3\', \'lightpink\': \'#FFB6C1\', \'lightsalmon\': \'#FFA07A\', \'lightseagreen\': \'#20B2AA\', \'lightskyblue\': \'#87CEFA\', \'lightslategray\': \'#778899\', \'lightsteelblue\': \'#B0C4DE\', \'lightyellow\': \'#FFFFE0\', \'lime\': \'#00FF00\', \'limegreen\': \'#32CD32\', \'linen\': \'#FAF0E6\', \'magenta\': \'#FF00FF\', \'maroon\': \'#800000\', \'mediumaquamarine\': \'#66CDAA\', \'mediumblue\': \'#0000CD\', \'mediumorchid\': \'#BA55D3\', \'mediumpurple\': \'#9370DB\', \'mediumseagreen\': \'#3CB371\', \'mediumslateblue\': \'#7B68EE\', \'mediumspringgreen\': \'#00FA9A\', \'mediumturquoise\': \'#48D1CC\', \'mediumvioletred\': \'#C71585\', \'midnightblue\': \'#191970\', \'mintcream\': \'#F5FFFA\', \'mistyrose\': \'#FFE4E1\', \'moccasin\': \'#FFE4B5\', \'navajowhite\': \'#FFDEAD\', \'navy\': \'#000080\', \'oldlace\': \'#FDF5E6\', \'olive\': \'#808000\', \'olivedrab\': \'#6B8E23\', \'orange\': \'#FFA500\', \'orangered\': \'#FF4500\', \'orchid\': \'#DA70D6\', \'palegoldenrod\': \'#EEE8AA\', \'palegreen\': \'#98FB98\', \'paleturquoise\': \'#AFEEEE\', \'palevioletred\': \'#DB7093\', \'papayawhip\': \'#FFEFD5\', \'peachpuff\': \'#FFDAB9\', \'peru\': \'#CD853F\', \'pink\': \'#FFC0CB\', \'plum\': \'#DDA0DD\', \'powderblue\': \'#B0E0E6\', \'purple\': \'#800080\', \'red\': \'#FF0000\', \'rosybrown\': \'#BC8F8F\', \'royalblue\': \'#4169E1\', \'saddlebrown\': \'#8B4513\', \'salmon\': \'#FA8072\', \'sandybrown\': \'#FAA460\', \'seagreen\': \'#2E8B57\', \'seashell\': \'#FFF5EE\', \'sienna\': \'#A0522D\', \'silver\': \'#C0C0C0\', \'skyblue\': \'#87CEEB\', \'slateblue\': \'#6A5ACD\', \'slategray\': \'#708090\', \'snow\': \'#FFFAFA\', \'springgreen\': \'#00FF7F\', \'steelblue\': \'#4682B4\', \'tan\': \'#D2B48C\', \'teal\': \'#008080\', \'thistle\': \'#D8BFD8\', \'tomato\': \'#FF6347\', \'turquoise\': \'#40E0D0\', \'violet\': \'#EE82EE\', \'wheat\': \'#F5DEB3\', \'white\': \'#FFFFFF\', \'whitesmoke\': \'#F5F5F5\', \'yellow\': \'#FFFF00\', \'yellowgreen\': \'#9ACD32\'} \'\'\'
import numpy as np import matplotlib.pyplot as plt # Have colormaps separated into categories: # http://matplotlib.org/examples/color/colormaps_reference.html cmaps = [(\'Perceptually Uniform Sequential\', [ \'viridis\', \'plasma\', \'inferno\', \'magma\']), (\'Sequential\', [ \'Greys\', \'Purples\', \'Blues\', \'Greens\', \'Oranges\', \'Reds\', \'YlOrBr\', \'YlOrRd\', \'OrRd\', \'PuRd\', \'RdPu\', \'BuPu\', \'GnBu\', \'PuBu\', \'YlGnBu\', \'PuBuGn\', \'BuGn\', \'YlGn\']), (\'Sequential (2)\', [ \'binary\', \'gist_yarg\', \'gist_gray\', \'gray\', \'bone\', \'pink\', \'spring\', \'summer\', \'autumn\', \'winter\', \'cool\', \'Wistia\', \'hot\', \'afmhot\', \'gist_heat\', \'copper\']), (\'Diverging\', [ \'PiYG\', \'PRGn\', \'BrBG\', \'PuOr\', \'RdGy\', \'RdBu\', \'RdYlBu\', \'RdYlGn\', \'Spectral\', \'coolwarm\', \'bwr\', \'seismic\']), (\'Qualitative\', [ \'Pastel1\', \'Pastel2\', \'Paired\', \'Accent\', \'Dark2\', \'Set1\', \'Set2\', \'Set3\', \'tab10\', \'tab20\', \'tab20b\', \'tab20c\']), (\'Miscellaneous\', [ \'flag\', \'prism\', \'ocean\', \'gist_earth\', \'terrain\', \'gist_stern\', \'gnuplot\', \'gnuplot2\', \'CMRmap\', \'cubehelix\', \'brg\', \'hsv\', \'gist_rainbow\', \'rainbow\', \'jet\', \'nipy_spectral\', \'gist_ncar\'])] nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps) gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) def plot_color_gradients(cmap_category, cmap_list, nrows): fig, axes = plt.subplots(nrows=nrows) fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99) axes[0].set_title(cmap_category + \' colormaps\', fontsize=14) for ax, name in zip(axes, cmap_list): ax.imshow(gradient, aspect=\'auto\', cmap=plt.get_cmap(name)) pos = list(ax.get_position().bounds) x_text = pos[0] - 0.01 y_text = pos[1] + pos[3]/2. fig.text(x_text, y_text, name, va=\'center\', ha=\'right\', fontsize=10) # Turn off *all* ticks & spines, not just the ones with colormaps. for ax in axes: ax.set_axis_off() for cmap_category, cmap_list in cmaps: plot_color_gradients(cmap_category, cmap_list, nrows) plt.show()
刻度、标题、标签和图例
legend ():生成默认图例, matplotlib 中的 legend 图例就是为了帮我们展示出 每个数据对应的图像名称. 更好的让读者认识到你的数据结构.。
xlabel、ylabel:设置X轴Y轴标签。
title:设置标题。
xlim、ylim:控制图标的范围。
xticks、yticks: 控制图标的刻度。
gca获取当前坐标轴信息。使用spines设置边框,使用set_color设置边框颜色: 默认白色。
解决中文显示问题:
mpl.rcParams[\'font.sans-serif\'] = [\'SimHei\']
mpl.rcParams[\'axes.unicode_minus\'] = False
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams[\'font.sans-serif\'] = [\'SimHei\'] mpl.rcParams[\'axes.unicode_minus\'] = False data = np.arange(-3,3,0.1) x = np.sin(data) y = np.cos(data) # 创建图形 fig = plt.figure() # 画图 plt.plot(x,y,\'r--\',label = \'x-line\') # 生成图例 plt.legend(loc=\'upper left\') #如果没有loc参数则是自动适应 # plt.legend(loc=\'lower right\') #如果没有loc参数则是自动适应 #设置标题 plt.title(\'进球数\') # 设置x/y轴标签 plt.xlabel(\'x轴\') plt.ylabel(\'y轴\') # 设置刻度的范围 # plt.xlim(1,10) # plt.ylim(1,10) # 设置图标的刻度 plt.xticks(np.arange(1,6,1),[\'中国\',\'2月\',\'3月\',\'4月\',\'5月\']) # plt.xticks(np.arange(1,6,1),[str(i)+\'月\' for i in range(1,6,1)]) plt.yticks(np.arange(1,10)) #写入文本 plt.text(2,6,\'这是一个练习图\') #相对于坐标轴 fig.text(0.5,0.5,\'this is test\') #相对于画布 # 说明: # plt.text()依次传入坐标和字符串内容 # x,y 代表传入柱的位置和高度 # \'%.2f\' 代表传入字符串的内容 # ha=\'center\' 设置文字水平对齐方式,其他参数查看帮助文档 # va=\'bottom\' 设置文字垂直对齐方式,其他参数查看帮助文档 # size 设置字体大小 # 获取坐标轴信息 ax = plt.gca() ax.spines[\'right\'].set_color(None) ax.spines[\'top\'].set_color(None) # ax.spines[\'left\'].set_color(None) # ax.spines[\'bottom\'].set_color(None) # plt.axis(\'off\') # 展示图片 plt.show()
#其中’loc’参数有多种,’best’表示自动分配最佳位置,其余的如下: \'best\' : 0, \'upper right\' : 1, \'upper left\' : 2, \'lower left\' : 3, \'lower right\' : 4, \'right\' : 5, \'center left\' : 6, \'center right\' : 7, \'lower center\' : 8, \'upper center\' : 9, \'center\' : 10,
设置坐标轴
# Annotation 标注 # 画出基本图 #当图线中某些特殊地方需要标注时,我们可以使用 annotation. matplotlib 中的 annotation 有两种方法, #一种是用 plt 里面的 annotate,一种是直接用 plt 里面的 text 来写标注. \'\'\'首先,我们在坐标轴中绘制一条直线.\'\'\' import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3, 3, 50) y = 2*x + 1 plt.figure(num=1, figsize=(8, 5),) plt.plot(x, y,) \'\'\'移动坐标\'\'\' #使用plt.gca获取当前坐标轴信息. 使用.spines设置边框:右侧边框;使用.set_color设置边框颜色:默认白色; 使用.spines设置边框:上边框;使用.set_color设置边框颜色:默认白色; ax = plt.gca() ax.spines[\'right\'].set_color(\'none\') ax.spines[\'top\'].set_color(\'none\') #然后我们挪动坐标轴的位置.使用.xaxis.set_ticks_position设置x坐标刻度数字或名称的位置:bottom.(所有位置:top,bottom,both,default,none) ax.xaxis.set_ticks_position(\'bottom\') #使用.spines设置边框:x轴;使用.set_position设置边框位置:y=0的位置;(位置所有属性:outward,axes,data) ax.spines[\'bottom\'].set_position((\'data\', 0)) #使用.yaxis.set_ticks_position设置y坐标刻度数字或名称的位置:left.(所有位置:left,right,both,default,none) ax.yaxis.set_ticks_position(\'left\') #使用.spines设置边框:y轴;使用.set_position设置边框位置:x=0的位置;(位置所有属性:outward,axes,data) ax.spines[\'left\'].set_position((\'data\', 0)) \'\'\'标注出点(x0, y0)的位置信息.\'\'\' x0 = 1 y0 = 2*x0 + 1 plt.plot([x0, x0,], [0, y0,], \'k--\', linewidth=2.5) plt.scatter([x0, ], [y0, ], s=50, color=\'b\') \'\'\'添加注释 annotate\'\'\' # 其中参数xycoords=\'data\' 是说基于数据的值来选位置, xytext=(+30, -30) 和 textcoords=\'offset points\' 对于标注位置的描述 和 xy 偏差值, arrowprops是对图中箭头类型的一些设置. plt.annotate(r\'$2x+1=%s$\' % y0, xy=(x0, y0), xycoords=\'data\', xytext=(+30, -30), textcoords=\'offset points\', fontsize=16, arrowprops=dict(arrowstyle=\'->\', connectionstyle="arc3,rad=.2")) \'\'\'添加注释 text \'\'\' plt.text(-3.7, 3, r\'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$\',fontdict={\'size\': 16, \'color\': \'r\'}) plt.show()
from mpl_toolkits.axisartist.axislines import SubplotZero import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np # 设置中文显示 mpl.rcParams[\'font.sans-serif\'] = [\'SimHei\'] mpl.rcParams[\'axes.unicode_minus\'] = False fig = plt.figure() ax = SubplotZero(fig, 111) fig.add_subplot(ax) for direction in ["xzero", "yzero"]: # adds arrows at the ends of each axis ax.axis[direction].set_axisline_style("-|>") # adds X and Y-axis from the origin ax.axis[direction].set_visible(True) for direction in ["left", "right", "bottom", "top"]: # hides borders ax.axis[direction].set_visible(False) x = [i for i in range(-10,11)] y = [8 for i in range(len(x))] ax.plot(x, y,\'-b\',label=\'y=8\') plt.xlim(-10,10) plt.ylim(-10,10) # ax.axis[\'yzero\'].set_label(\'x轴\') # ax.axis[\'xzero\'].set_label(\'y轴\') plt.xticks(x) plt.yticks(x) plt.legend(loc=\'lower right\') plt.show()
import math import matplotlib as mpl import matplotlib.pyplot as plt import mpl_toolkits.axisartist as axisartist # 设置中文显示 mpl.rcParams[\'font.sans-serif\'] = [\'SimHei\'] mpl.rcParams[\'axes.unicode_minus\'] = False # 创建画布 fig = plt.figure(figsize=(16, 8)) # 使用axisartist.Subplot方法创建一个绘图区对象ax ax = axisartist.Subplot(fig, 111) # 将绘图区对象添加到画布中 fig.add_axes(ax) # 通过set_visible方法设置绘图区所有坐标轴隐藏 ax.axis[:].set_visible(False) # ax.new_floating_axis代表添加新的坐标轴 ax.axis["x"] = ax.new_floating_axis(0, 0) # 第一个0表示水平线,第二个0表示经过0点。 # 给x坐标轴加上箭头 ax.axis["x"].set_axisline_style("->", size=1.0) # ->表示虚心箭头,size表示箭头的大小。 # 添加y坐标轴,且加上箭头 ax.axis["y"] = ax.new_floating_axis(1, 0) # 1表示竖线,第二个0表示经过0点。 ax.axis["y"].set_axisline_style("-|>", size=1.0) # -|>表示虚心箭头,size表示箭头的大小。 # 设置x、y轴上刻度显示方向 ax.axis["x"].set_axis_direction("top") ax.axis["y"].set_axis_direction("right") x = [i / 10 for i in range(-100, 101)] y = [math.sin(i) for i in x] plt.plot(x, y, \'-b\', label=\'y=sin(x)\') y1 = [2 ** i for i in x] plt.plot(x, y1, \'-k\', label=\'y=2^x\') x2 = [i / 10 for i in range(1, 101)] y2 = [math.log(i, 2) for i in x2] plt.plot(x2, y2, \'-r\', label=\'y=log2x\') plt.plot(x, x, \'-g\', label=\'y=x\') # 生成图例 plt.legend(loc=\'lower right\') # 设置x轴和y轴的取值范围 plt.xlim(-10, 10) plt.ylim(-10, 10) # 设置x轴和y轴标签名 plt.xlabel(\'x轴\') plt.ylabel(\'y轴\') # 设置显示网格 plt.grid(True) plt.show()
tick 能见度
#当图片中的内容较多,相互遮盖时,我们可以通过设置相关内容的透明度来使图片更易于观察,也即是通过本节中的bbox参数设置来调节图像信息. import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3, 3, 50) y = 0.1*x plt.figure() # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序 plt.plot(x, y, linewidth=10, zorder=1) plt.ylim(-2, 2) ax = plt.gca() ax.spines[\'right\'].set_color(\'none\') ax.spines[\'top\'].set_color(\'none\') ax.xaxis.set_ticks_position(\'bottom\') ax.spines[\'bottom\'].set_position((\'data\', 0)) ax.yaxis.set_ticks_position(\'left\') ax.spines[\'left\'].set_position((\'data\', 0)) \'\'\'然后对被遮挡的图像调节相关透明度,本例中设置 x轴 和 y轴 的刻度数字进行透明度设置\'\'\' #中label.set_fontsize(12)重新调节字体大小,bbox设置目的内容的透明度相关参,facecolor调节 box 前景色,edgecolor 设置边框, 本处设置边框为无,alpha设置透明度. for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_fontsize(12) # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序 label.set_bbox(dict(facecolor=\'white\', edgecolor=\'None\', alpha=0.7, zorder=2)) # label.set_bbox(dict(facecolor=\'red\', edgecolor=\'None\', alpha=0.7, zorder=2)) print(ax.get_xticklabels()+ ax.get_yticklabels()) plt.show()
Subplot 子图
subplot:子图,figure对象下创建一个或多个subplot对象(即axes) 用于绘制图像。 subplot(numRows, numCols, plotNum)。
x1 = [1,3,5] y1 = [2,4,5] x2 = [1,4,5] y2 = [3,2,5] # 创建图形 plt.figure() plt.subplot(221) plt.plot(x1,y1,\'r--\') plt.subplot(223) plt.plot(x2,y2,\'b-\') plt.show()
Sublots():返回一个图像和多个子图。
参数:
nrows=x, ncols=x, sharex=True, sharey=False, gridspec_kw={\'height_ratios\':[2,2,1,1]}
例:
fig, ax = plt.subplots(2,2),其中参数分别代表子图的行数和列数,一共有 2x2 个图像。函数返回 一个figure图像和一个子图ax的array列表。
# 生成一个figure 以及子图的列表 fig, ax = plt.subplots(2,2) # 2行 2列 2维列表 for i in range(2): for j in range(2): ax[i][j].plot(np.random.randn(50).cumsum(),\'r--\') # ax[i,j].plot(np.random.randn(50).cumsum(),\'r--\') fig, ax = plt.subplots(2,2) # 2行 2列 2维列表 colors=[\'Reds\',\'Blues\'] for i in range(2): for j in range(2): ax1=ax[i][j].scatter(np.random.randn(50).cumsum(),np.random.randn(50),c=np.random.randn(50),cmap=colors[i]) fig.colorbar(ax1,ax=ax[i][j]) #参数mappable理解起来就是我们需要提供一个可以映射颜色的对象,这个对象就是我们作的图,参数ax用来指示colorbar()获取到的渐变色条在哪里显示,ax参数设置成多个Axes对象。 plt.show() \'\'\'图像保存\'\'\' plt.savefig(\'zitu.jpg\')
子图面向对象的形式:
fig = plt.figure() #Figure实例,可以添加Axes实例。 ax = fig.add_subplot(111) #返回Axes实例 参数1,子图的总行数 参数2,子图的总列数 参数3,子图位置 在Figure上添加子图的常用方法。
# 创建图形 fig= plt.figure() fig.suptitle(\'运行效果\') #设置总标题 ax1 = fig.add_subplot(321,facecolor=\'b\') #添加子图背景颜色 ax1.plot(np.random.randn(50).cumsum(),\'r--\') plt.title(\'this is test\') ax2 = fig.add_subplot(322,facecolor=\'r\') ax2.plot(np.random.randn(50).cumsum(),\'b-\') plt.title(\'这是一个测试\') ax3 = fig.add_subplot(312) ax3.plot(np.random.randn(50).cumsum(),\'y--\') ax4 = fig.add_subplot(325) ax4.plot(np.random.randn(50).cumsum(),\'g-\') ax4.set_title(\'this is test\') ax5 = fig.add_subplot(326) ax5.plot(np.random.randn(50).cumsum(),\'g-\') ax5.set_title(\'这是一个测试\') plt.show()
利用subplot_adjust()函数可以对画的多个子图进行调整,优化间隔,它一共有left、right, bottom, top, wspace, hspase 六个参数,取 值从0至1。
# 创建图形 fig= plt.figure(figsize=(10,10)) #设置总标题 # fig.suptitle(\'运行效果\') plt.suptitle(\'运行结果\') ax1 = fig.add_subplot(221,facecolor=\'b\') #添加子图背景颜色 ax1.plot(np.random.randn(50).cumsum(),\'r--\') plt.title(\'this is test\') ax2 = fig.add_subplot(222,facecolor=\'r\') ax2.plot(np.random.randn(50).cumsum(),\'b-\') plt.title(\'这是一个测试\') ax3 = fig.add_subplot(223) ax3.plot(np.random.randn(50).cumsum(),\'y--\') ax5 = fig.add_subplot(224) ax5.plot(np.random.randn(50).cumsum(),\'g-\') fig.subplots_adjust(wspace=0,hspace=0) plt.show() #画了多个子图时,在保存的时候出现了以下问题,就是子图之间有重叠。这种情况发生在我调用函数画图后,函数返回一个fig对象(fig=plt.gcf()),利用下面这行: # plt.savefig(savefig_path, bbox_inches=\'tight\', dpi=300) #bbox_inches=\'tight\'帮助删除图片空白部分
共用x轴
import numpy as np import matplotlib.pyplot as plt t = np.arange(0.01, 10.0, 0.01) data1 = np.exp(t) data2 = np.sin(2 * np.pi * t) fig, ax1 = plt.subplots() color = \'tab:red\' ax1.set_xlabel(\'time (s)\') ax1.set_ylabel(\'exp\', color=color) ax1.plot(t, data1, color=color) ax1.tick_params(axis=\'y\', labelcolor=color) ax2 = ax1.twinx() color = \'tab:blue\' ax2.set_ylabel(\'sin\', color=color) ax2.plot(t, data2, color=color) ax2.tick_params(axis=\'y\', labelcolor=color) plt.xticks(rotation=50) #如果不是共用轴,就可以设置。现在共用X轴就无法使用xticks的rotation来对x周标签旋转 fig.tight_layout() plt.show()
常用图形
柱状图
matplotlib.pyplot. bar (*args, **kwargs) bar(left, height, width, bottom, * args, align=\'center\', **kwargs)。
参数:
left:数据标量。
height:高。
width:款。
bottom:底端对应Y轴。
align:对齐如果为 "居中", 则将x参数解 释为条形中心的坐标。如果 "边缘", 将条形按其左边缘对齐要对齐右边缘的条形图, 可传递负的宽度和对 align=\'edge\'
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams[\'font.sans-serif\'] = [\'SimHei\'] mpl.rcParams[\'axes.unicode_minus\'] = False # 设置jupyter中 的显示方式 # %matplotlib tk %matplotlib inline # 设置数据 height = np.array([100,200,300,400]) # y # 设置数据标量 left = np.arange(1,5,1) # 4 x # 设置柱子宽度 n = 4 width = 0.8/4 # 创建figure plt.figure() # 画图 plt.bar(left,height,width = width,color = \'lightskyblue\',align = \'center\',label = \'上海\') plt.bar(left-width,height+20,width = width,color = \'red\',align = \'center\',label = \'北京\') plt.bar(left+width,height+10,width = width,color = \'yellowgreen\',align = \'center\',label = \'深圳\') # 生成图例 plt.legend(loc=\'upper left\') #设置标题 plt.title(\'旅游人数\') #要改 # 设置x/y轴标签 # 要改 plt.xlabel(\'月份\') plt.ylabel(\'人次/百万\') # 设置图标的刻度 plt.xticks(np.arange(1,5,1),[\'1月\',\'2月\',\'3月\',\'4月\']) # 要改 # plt.xticks(np.arange(1,6,1),[str(i)+\'月\' for i in range(1,6,1)]) plt.yticks(np.arange(100,600,100)) # 获取坐标轴信息 ax = plt.gca() ax.spines[\'right\'].set_color(None) ax.spines[\'top\'].set_color(None) # 展示图片 plt.show()
# 设置画板大小 plt.figure(figsize=(10, 6)) # 画出柱状图 plt.barh(left, height, 0.5, color=[\'r\', \'g\', \'b\',\'y\']) plt.show()
直方图
matplotlib.pyplot.hist( x,bins=10,range=None,normed=False,weights=None,cumulative=False,bottom=None, histtype=\'bar\', align=\'mid\',orientation=u\'vertical\', rwidth=None, log=False,color=None, label=None,stacked=False,hold=None,**kwargs) 。
-- x: 一个列表或者多个列表(表示不同数据集,长度可以不一致)。
– range: 元组 – weights: x里每个元素对bin高度的贡献(默认为1)。
– bottom: 数字或者长度为bins的列表。
– histtype: [\'bar\' | \'barstacked\' | \'step\' | \'stepfilled\']。
– align: [\'left\' | \'mid\' | \'right\']。
– orientation: [\'horizontal\' | \'vertical\']。
– rwidth: bar相对bin的宽度。
– color: 一种颜色或者颜色列表(针对不同数据集)。
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams[\'font.sans-serif\'] = [\'SimHei\'] mpl.rcParams[\'axes.unicode_minus\'] = False # 设置jupyter中 的显示方式 # %matplotlib tk %matplotlib inline # 设置数据 mu , sigma = 100,15 # x = np.random.randn(10000)*mu*sigma x = np.random.randn(10000).cumsum() plt.figure() plt.hist(x,1000,alpha = 0.5,color = \'red\') plt.title(\'频率图\') plt.grid(True) plt.show()
散点图
matplotlib.pyplot. scatter (x, y, s=none, c=none, marker=none, cmap= None, norm=none, vmin=none, vmax=none, alpha=none, Linewidths=none, verts=none, edgecolors=none, hold=none, data= None, **kwargs)。
参数:
x,y:相同长度的数组序列。
s :散点的大小标量或形同数组,可选参数,默认20。
c :散点的色彩或颜色序列,可选。
maker:标记风格,可选,默认是‘o’。
norm:数据的亮度。
alpha:散点的透明度
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams[\'font.sans-serif\'] = [\'SimHei\'] mpl.rcParams[\'axes.unicode_minus\'] = False # 设置jupyter中 的显示方式 # %matplotlib tk %matplotlib inline # 设置数据 x = np.random.randn(1000) y = np.random.randn(1000) plt.scatter(x,y,c = np.random.rand(1000,4),s = np.random.rand(1000)*50,alpha = 0.7) plt.title(\'aaa\') plt.show()
饼图
matplotlib.pyplot. pie(x, explode=None, labels=None, colors=(\'b\', \'g\', \'r\', \'c\', \'m\', \'y\', \'k\', \'w\'), autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None, counterclock=True, wedgeprops=None, textprops=None, center = (0, 0), frame = False )
参数:
x (每一块)的比例,如果sum(x) > 1会使用sum(x)归一化。
labels (每一块)饼图外侧显示的说明文字。
explode (每一块)离开中心距离。
startangle 起始绘制角度,默认图是从x轴正方向逆时针画起,如设定=90则从y轴正方向画起。
shadow 是否阴影。
labeldistance label绘制位置,相对于半径的比例, 如<1则绘制在饼图内侧。
autopct 控制饼图内百分比设置,可以使用format字符串或者format function \'%1.1f\'指小数点前后位数(没有用空格补齐)。
pctdistance 类似于labeldistance,指定autopct的位置刻度。
radius 控制饼图半径。
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd # 设置中文显示 mpl.rcParams[\'font.sans-serif\'] = [\'SimHei\'] mpl.rcParams[\'axes.unicode_minus\'] = False # 设置jupyter中 的显示方式 # %matplotlib tk %matplotlib inline # 设置数据 x = [15,25,30,30] # 设置颜色 color = [\'r\',\'yellow\',\'green\',\'blue\'] # 设置每一块离开中心的距离 explode = [0,0.1,0,0] # 每一块的文字说明 labels = [\'娱乐\',\'日常生活\',\'女朋友\',\'游戏\'] plt.figure() # 绘制饼图 plt.pie(x,explode = explode,labels = labels , colors = color,startangle = 90,shadow = True,labeldistance = 1.1,autopct = \'%.1f%%\') # 设置圆图 plt.axis(\'equal\') plt.title(\'月工资分配\') plt.show()
箱式图(.boxplot()函数)
箱线图通过数据的四分位数来展示数据的分布情况。箱线图把数据从小到大进行排列并等分成四份,第一分位数(Q1),第二分位数(Q2)和第三分位数(Q3)分别为数据的第25%,50%和75%的数字。
箱线图分为两部分,分别是箱(box)和须(whisker)。箱(box)用来表示从第一分位到第三分位的数据,须(whisker)用来表示数据的范围。
箱线图从上到下各横线分别表示:数据上限(通常是Q3+1.5XIQR),第三分位数(Q3),第二分位数(中位数),第一分位数(Q1),数据下限(通常是Q1-1.5XIQR)。有时还有一些圆点,位于数据上下限之外,表示异常值(outliers)。
import matplotlib.pyplot as plt import numpy as np # figsize=(8, 6)即figure窗口大小800X600像素 fig, ax = plt.subplots(2, 2, figsize=(8, 6)) # 创建x数据 y = np.random.normal(0, 1, 1000) # 画箱式图 ax[0, 0].boxplot(y) ax[0, 1].boxplot(y, vert=False) plt.show() plt.close()
极坐标图
import matplotlib.pyplot as plt import numpy as np # figsize=(8, 6)即figure窗口大小800X600像素 fig = plt.figure(figsize=(8, 6)) ax1 = fig.add_subplot(121, projection=\'polar\') ax2 = fig.add_subplot(122, projection=\'polar\') N = 30 # 将极坐标均分为N份 thetas = np.linspace(0, 2 * np.pi, N, endpoint=False) # 取一个随机的角度 turn_rads = 10 * np.random.rand(N) # 取一个随机的宽度 widths = np.pi / 4 * np.random.rand(N) # 从哪个角度开始画,画过多少角度长度,画的扇形的半径,从距离圆心0的地方开始画 ax1.bar(thetas, turn_rads, width=widths, facecolor=\'green\', bottom=0.0, alpha=0.5) ax2.bar(thetas, turn_rads, width=widths, facecolor=\'red\', bottom=2, alpha=0.5) plt.show() plt.close()
等高线图(.contour()和.contourf()函数)
等高线地图就是将地表高度相同的点连成一环线直接投影到平面形成水平曲线。在机器学习中也会被用在绘制梯度下降算法的图形中。
等高线图:等高线地图就是将地表高度相同的点连成一环线直接投影到平面形成水平曲线。不同高度的环线不会相合,除非地表显示悬崖或峭壁才能使某处线条太密集出现重叠现像,若地表出现平坦开阔的山坡,曲线间之距离就相当宽。
contourf 填充颜色函数
- 前三个参数 X, Y, Height 用来引进点的位置和对应的高度数据;
- 数字 10 代表将等高线图分成10块(这里不是硬性要求,但数值过小会造成部分分区颜色区分度不高);
- alpha = 0.6 用来设置填充颜色的范围,alpha取值为 [0,1) 。alpha=0时,画出的是无色图,alpha越接近1,颜色的搭配就越向深。
contour 绘制等高线函数
- 前面的参数跟contourf一样;
- colors = ‘black’ 代表线条颜色是黑色;
- linewidth = 0.5 代表线条粗细.
如果遇到不能靠单纯输入各点高度值的情况,就需要将Height数组变成一个以横纵坐标X和Y为参数的高度计算函数:
def f(x, y): return x * y #这里的函数是我简单定义的,要根据现实情况设置符合实际的函数
import numpy as np import matplotlib.pyplot as plt # 定义等高线图的横纵坐标x,y #从左边取值为从 -3 到 3 ,各取5个点,一共取 5*5 = 25 个点 x = np.linspace(-3, 3, 5) y = np.linspace(-3, 3, 5) # 将原始数据变成网格数据 X, Y = np.meshgrid(x, y) # 定义等高线高度函数 def f(x, y): return x * y # 填充颜色 plt.contourf(X, Y, f(X,Y), 10, alpha = 0.5, cmap = plt.cm.hot) # 绘制等高线 C = plt.contour(X, Y, f(X,Y), 10, colors = \'black\', linewidth = 0.5) # 显示各等高线的数据标签 plt.clabel(C, inline = True, fontsize = 10) # 去除坐标轴 plt.xticks(()) plt.yticks(()) plt.show()
import numpy as np import matplotlib.pyplot as plt # 定义等高线图的横纵坐标x,y #从左边取值为从 -3 到 3 ,各取5个点,一共取 5*5 = 25 个点 x = np.linspace(-3, 3, 5) y = np.linspace(-3, 3, 5) # 将原始数据变成网格数据 X, Y = np.meshgrid(x, y) # 各地点对应的高度数据 #Height是个 5*5 的数组,记录地图上 25 个点的高度汇总 Height = [[0,0,1,2,2],[0,-2,-2,1,5],[4,2,6,8,1],[3,-3,-3,0,5],[1,-5,-2,0,3]] # 填充颜色 plt.contourf(X, Y, Height, 10, alpha = 0.6, cmap = plt.cm.hot) # 绘制等高线 C = plt.contour(X, Y, Height, 10, colors = \'black\', linewidth = 0.5) # 显示各等高线的数据标签 plt.clabel(C, inline = True, fontsize = 10) plt.show()
import matplotlib.pyplot as plt import numpy as np fig, ax = plt.subplots(2, 2, figsize=(10, 6)) # 创建x数据和y数据 x = np.linspace(-2, 2, 100) y = np.linspace(-2, 2, 100) # meshgrid函数使用x和y的数组的值作为x轴和y轴坐标点在平面上确定一个点,这个点的值是Z,Z大小关系到颜色的深浅。 # 具体来说,就是将x这个100个数值的一维向量按行复制100行,变成X其shape=(100,100)的二维向量,y值也是这么处理的 # 注意x和y的shape都是(100,),而X和Y的shape为(100,100)和(100,100) X, Y = np.meshgrid(x, y) # 注意计算Z要用X和Y计算,这样计算出来的Z的shape=(100,100),画图时数据的shape才能对的上,否则会报错 Z = (1 - X ** 2 + X ** 5 + Y ** 3) * np.exp(-X ** 2 - Y ** 2) # Z通常表示的是距离X-Y平面的距离,传入X、Y则是控制了绘制等高线的范围。 # contourf会填充轮廓线之间的颜色,而contour不会填充轮廓线之间的颜色 # 10指等高线图划分成10个不同范围的区域,alpha指透明度,cmap=plt.get_cmap(\'hot\')指填充用的颜色域 ax[0, 0].contourf(X, Y, Z, 10, alpha=0.75, cmap=plt.get_cmap(\'hot\')) # 在ax[0, 0]的contourf图中绘制等高线 C = ax[0, 0].contour(X, Y, Z, 10, colors=\'black\') # 显示各等高线的数据标签 ax[0, 0].clabel(C, inline=True, fontsize=10) # ax[0, 1]也是等高线图,但这个图没有填充轮廓线之间的颜色 D = ax[0, 1].contour(X, Y, Z, 10, alpha=0.75, colors=\'red\') # 显示各等高线的数据标签 ax[0, 1].clabel(D, inline=True, fontsize=10) ax[1, 0].contour(X, Y, Z, 30, alpha=0.75, colors=\'blue\') plt.show() plt.close()
3D图
3D图在机器学习和深度学习中观察local minima点和global minima点时十分方便。3D图可以旋转角度,以找到最佳的观察角度。
from mpl_toolkits.mplot3d import Axes3D # 画3D图所需要的包 import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(8, 6)) ax = Axes3D(fig) # 创建x数据和y数据 x = np.linspace(-2, 2, 100) y = np.linspace(-2, 2, 100) # meshgrid函数使用x和y的数组的值作为x轴和y轴坐标点在平面上画网格。 # 具体来说,就是将x这个100个数值的一维向量按行复制100行,变成X其shape=(100,100)的二维向量,y值也是这么处理的 # 注意x和y的shape都是(100,),而X和Y的shape为(100,100)和(100,100) X, Y = np.meshgrid(x, y) # 注意计算Z要用X和Y计算,这样计算出来的Z的shape=(100,100),画图时数据的shape才能对的上,否则会报错 Z = (1 - X ** 2 + X ** 5 + Y ** 3) * np.exp(-X ** 2 - Y ** 2) # Z通常表示的是距离X-Y平面的距离,传入X、Y则是控制了绘制等高线的范围。 # rstride=1, cstride=1指x方向和y方向的色块大小,可以不指定 ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap(\'hot\')) # 画出3D图对应的等高线图,该等高线图的z轴值全部压缩到-1,也就是说这个图在z=-1的位置,和X-Y平面平行 ax.contourf(X, Y, Z, zdir=\'z\', offset=-1, cmap=\'hot\') plt.show() plt.close()
三维线图
Axes3D.plot(xs, ys, *args, **kwargs)
参数:
- xs, ys:x, y coordinates of vertices。
- zs:z value(s), either one for all points or one for each point.
- zdir:Which direction to use as z (‘x’, ‘y’ or ‘z’) when plotting a 2D set.
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np %matplotlib tk # 构造一个3D画板 fig = plt.figure() ax = Axes3D(fig) x = np.arange(-2, 2, 0.1) y = np.arange(-2, 2, 0.1) def f(x, y): return (x**2 + y**2) # 传入(x,y,z)坐标 ax.plot(x, y, f(x, y), color=\'r\') # 画图 # 设置标签 ax.set_xlabel(\'x label\') ax.set_ylabel(\'y label\') ax.set_zlabel(\'z label\') plt.show()
三维平面图
Axes3D.plot_surface(X, Y, Z, *args, **kwargs)
参数:
- X, Y, Z:Data values as 2D arrays。
- rstride:Array row stride (step size)。
- cstride:Array column stride (step size)
- rcount:Use at most this many rows, defaults to 50
- ccount:Use at most this many columns, defaults to 50
- color:Color of the surface patches
- cmap:A colormap for the surface patches.
- facecolors:Face colors for the individual patches
- norm:An instance of Normalize to map values to colors
- vmin:Minimum value to map
- vmax:Maximum value to map
- shade:Whether to shade the facecolors
# 构造空间图 # 构造一个3D画板 fig = plt.figure() ax = Axes3D(fig) x = np.arange(-2, 2, 0.1) y = np.arange(-2, 2, 0.1) # 将x,y构成点矩阵 x, y = np.meshgrid(x, y) def f(x, y): return (x**2 + y**2) # 传入(x,y,z)坐标 ax.plot_surface(x, y, f(x, y), color=\'r\') # 画图 # 设置标签 ax.set_xlabel(\'x label\') ax.set_ylabel(\'y label\') ax.set_zlabel(\'z label\') plt.show()
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import numpy as np fig = plt.figure() ax = fig.gca(projection=\'3d\') # Make data. X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X ** 2 + Y ** 2) Z = np.sin(R) # Plot the surface. surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False) # Customize the z axis. ax.set_zlim(-1.01, 1.01) ax.zaxis.set_major_locator(LinearLocator(10)) ax.zaxis.set_major_formatter(FormatStrFormatter(\'%.02f\')) # Add a color bar which maps values to colors. fig.colorbar(surf, shrink=0.5, aspect=5) plt.show()
三维散点图
Axes3D.scatter(xs, ys, zs=0, zdir=\'z\', s=20, c=None, depthshade=True, *args, **kwargs)
# 构造一个空间散点图 # 构造一个3D画板 fig = plt.figure() ax = Axes3D(fig) x = np.arange(-2, 2, 0.1) y = np.arange(-2, 2, 0.1) # 将x,y构成点矩阵 x, y = np.meshgrid(x, y) def f(x, y): return (x**2 + y**2) # 传入(x,y,z)坐标 ax.scatter3D(x, y, f(x, y), color=\'g\', marker=\'*\', s=10) # 画图 # 设置标签 ax.set_xlabel(\'x label\') ax.set_ylabel(\'y label\') ax.set_zlabel(\'z label\') plt.show()
线框图
Axes3D.plot_wireframe(X, Y, Z, *args, **kwargs)
参数:
- X, Y,:Data values as 2D arrays。
- rstride:Array row stride (step size), defaults to 1。
- cstride:Array column stride (step size), defaults to 1。
- rcount:Use at most this many rows, defaults to 50。
- ccount:Use at most this many columns, defaults to 50。
from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection=\'3d\') # Grab some test data. X, Y, Z = axes3d.get_test_data(0.05) # Plot a basic wireframe. ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) plt.show()
柱状图
Axes3D.bar(left, height, zs=0, zdir=\'z\', *args, **kwargs)
参数:
- left:The x coordinates of the left sides of the bars.。
- height:he height of the bars。
- zs:Z coordinate of bars, if one value is specified they will all be placed at the same z。
- zdir:Which direction to use as z (‘x’, ‘y’ or ‘z’) when plotting a 2D set.。
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection=\'3d\') for c, z in zip([\'r\', \'g\', \'b\', \'y\'], [30, 20, 10, 0]): xs = np.arange(20) ys = np.random.rand(20) # You can provide either a single color or an array. To demonstrate this, # the first bar of each set will be colored cyan. cs = [c] * len(xs) cs[0] = \'c\' ax.bar(xs, ys, zs=z, zdir=\'y\', color=cs, alpha=0.8) ax.set_xlabel(\'X\') ax.set_ylabel(\'Y\') ax.set_zlabel(\'Z\') plt.show()
箭头图
Axes3D.quiver(*args, **kwargs)
参数:
- X, Y, Z:The x, y and z coordinates of the arrow locations (default is tail of arrow; see pivot kwarg)。
- U, V, W:The x, y and z components of the arrow vectors。
from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.gca(projection=\'3d\') # Make the grid x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2), np.arange(-0.8, 1, 0.2), np.arange(-0.8, 1, 0.8)) # Make the direction data for the arrows u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z) v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z) w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) * np.sin(np.pi * z)) ax.quiver(x, y, z, u, v, w, length=0.1, normalize=True) plt.show()
2D转3D图
from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca(projection=\'3d\') # Plot a sin curve using the x and y axes. x = np.linspace(0, 1, 100) y = np.sin(x * 2 * np.pi) / 2 + 0.5 ax.plot(x, y, zs=0, zdir=\'z\', label=\'curve in (x,y)\') # Plot scatterplot data (20 2D points per colour) on the x and z axes. colors = (\'r\', \'g\', \'b\', \'k\') x = np.random.sample(20 * len(colors)) y = np.random.sample(20 * len(colors)) labels = np.random.randint(3, size=80) # By using zdir=\'y\', the y value of these points is fixed to the zs value 0 # and the (x,y) points are plotted on the x and z axes. ax.scatter(x, y, zs=0, zdir=\'y\', c=labels, label=\'points in (x,z)\') # Make legend, set axes limits and labels ax.legend() ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.set_zlim(0, 1) ax.set_xlabel(\'X\') ax.set_ylabel(\'Y\') ax.set_zlabel(\'Z\') # Customize the view angle so it\'s easier to see that the scatter points lie # on the plane y=0 ax.view_init(elev=20., azim=-35) plt.show()
文本图
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca(projection=\'3d\') # Demo 1: zdir zdirs = (None, \'x\', \'y\', \'z\', (1, 1, 0), (1, 1, 1)) xs = (1, 4, 4, 9, 4, 1) ys = (2, 5, 8, 10, 1, 2) zs = (10, 3, 8, 9, 1, 8) for zdir, x, y, z in zip(zdirs, xs, ys, zs): label = \'(%d, %d, %d), dir=%s\' % (x, y, z, zdir) ax.text(x, y, z, label, zdir) # Demo 2: color ax.text(9, 0, 0, "red", color=\'red\') # Demo 3: text2D # Placement 0, 0 would be the bottom left, 1, 1 would be the top right. ax.text2D(0.05, 0.95, "2D Text", transform=ax.transAxes) # Tweaking display region and labels ax.set_xlim(0, 10) ax.set_ylim(0, 10) ax.set_zlim(0, 10) ax.set_xlabel(\'X axis\') ax.set_ylabel(\'Y axis\') ax.set_zlabel(\'Z axis\') plt.show()
3D拼图
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data from matplotlib import cm import numpy as np # set up a figure twice as wide as it is tall fig = plt.figure(figsize=plt.figaspect(0.5)) # =============== # First subplot # =============== # set up the axes for the first plot ax = fig.add_subplot(1, 2, 1, projection=\'3d\') # plot a 3D surface like in the example mplot3d/surface3d_demo X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X ** 2 + Y ** 2) Z = np.sin(R) surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False) ax.set_zlim(-1.01, 1.01) fig.colorbar(surf, shrink=0.5, aspect=10) # =============== # Second subplot # =============== # set up the axes for the second plot ax = fig.add_subplot(1, 2, 2, projection=\'3d\') # plot a 3D wireframe like in the example mplot3d/wire3d_demo X, Y, Z = get_test_data(0.05) ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) plt.show()
案例
import numpy import matplotlib.pyplot as plt x1 = np.hstack((np.random.uniform(-1,1,(10000)),[1,-1])) x1 = x1[x1!=0] x1 = sorted(x1) x2 = np.array(list(reversed(x1))) X = np.hstack((x1,x2)).reshape((-1)) print(X) y1 = 0.6*np.abs(x1) + np.sqrt((1-np.square(x1))/3) y2 = 0.6*np.abs(x2) - np.sqrt((1-np.square(x2))/3) Y = np.hstack((np.array(y1),np.array(y2))).reshape((-1,)) plt.plot(X,Y,\'r\') plt.show()
动态图
动态图有助于我们实时地观察某个变量值的变化情况。
matplotlib可以实现动画,官方一共给了两种实现方式,分别是FuncAnimation和ArtistAnimation,FuncAnimationnc是用函数生成的动画,而ArtistAnimation是用一帧一帧的数据生成的动画。
FuncAnimation
官方文档:https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html
主要参数
fig: matplotlib.figure.Figure
- 用来画图、变化尺寸或者其他需要的事件的figure对象
func: callable
- 每一帧调用的函数。
- def func(frame, *fargs) -> iterable_of_artists:1
- 第一个参数是下一帧的值,任何额外的参数都可以通过fargs参数得到
frames: iterable, int, generator function, or None, optional
- 用来传递函数和动画的每一帧的数据源,控制帧的迭代
init_func : callable, optional
- 用来画初始帧的函数,这个函数只会在第一帧之前被调用一次。如果没有给出的话,那么帧序列中的第一帧将会用来替代。
- If blit == True, init_func必须返回可迭代形式
fargs: tuple or None, optional
- 传递给每一次func调用的额外的参数
save_count: int,optional
- 从帧到缓存的值的数量
interval : number, optional
- 帧间距(单位ms),默认200毫秒
repeat_delay : number, optional
- 动画循环间距,默认None
repeat : bool, optional
- 动画是否要循环播放,默认为True
blit : bool, optional
- 控制是否使用blitting来优化绘图
import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from IPython import display fig, ax = plt.subplots() xdata, ydata = [], [] ln, = ax.plot([], [], \'r-\', animated=False) def init(): ax.set_xlim(0, 2*np.pi) ax.set_ylim(-1, 1) return ln, def update(frame): xdata.append(frame) ydata.append(np.sin(frame)) ln.set_data(xdata, ydata) return ln, # func是更新图形的函数,frames是总共更新的次数,intit_func是图形初始化函数,interval是更新的间隔时间(ms) # blit决定是更新整张图的点(Flase)还是只更新变化的点(True) ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128), init_func=init, blit=True) #%matplotlib inline 可以在Ipython编译器比如jupyter notebook 或者 jupyter qtconsole里直接使用,功能是可以内嵌绘图,并且省略掉plt.show()。 %matplotlib inline ani
import math import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation def beta_pdf(x, a, b): return (x**(a-1) * (1-x)**(b-1) * math.gamma(a + b) / (math.gamma(a) * math.gamma(b))) class UpdateDist(object): def __init__(self, ax, prob=0.5): self.success = 0 self.prob = prob self.line, = ax.plot([], [], \'k-\') self.x = np.linspace(0, 1, 200) self.ax = ax # Set up plot parameters self.ax.set_xlim(0, 1) self.ax.set_ylim(0, 15) self.ax.grid(True) # This vertical line represents the theoretical value, to # which the plotted distribution should converge. self.ax.axvline(prob, linestyle=\'--\', color=\'black\') def init(self): self.success = 0 self.line.set_data([], []) return self.line, def __call__(self, i): # This way the plot can continuously run and we just keep # watching new realizations of the process if i == 0: return self.init() # Choose success based on exceed a threshold with a uniform pick if np.random.rand(1,) < self.prob: self.success += 1 y = beta_pdf(self.x, self.success + 1, (i - self.success) + 1) self.line.set_data(self.x, y) return self.line, # Fixing random state for reproducibility np.random.seed(19680801) fig, ax = plt.subplots() ud = UpdateDist(ax, prob=0.7) anim = FuncAnimation(fig, ud, frames=np.arange(100), init_func=ud.init, interval=300, blit=True) %matplotlib inline anim
import matplotlib.pyplot as plt import matplotlib.animation import numpy as np t = np.linspace(0,2*np.pi) x = np.sin(t) fig,ax = plt.subplots(1,1) ax.axis([0,2*np.pi,-1,1]) l, = ax.plot([],[]) def animate(i): l.set_data(t[:i], x[:i]) ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t)) \'\'\'保存图片\'\'\' # ani.save(\'sin_dot.gif\', writer=\'imagemagick\', fps=30) \'\'\'读取图片\'\'\' # from ipywidgets import Image # from IPython import display # animatedGif = "sin_dot.gif" #path relative to your notebook # file = open(animatedGif , "rb") # image = file.read() # progress= Image( # value=image, # format=\'gif\', # width=500, # height=500) # display.display(progress) # %matplotlib inline # #progress.close() \'\'\'从matplotlib 2.1开始,我们可以使用JavaScript创建动画.这与ani.to_html5()解决方案类似,不同之处在于它不需要任何视频编解码器。\'\'\' from IPython.display import HTML %matplotlib inline HTML(ani.to_jshtml()) #或者,将jsanimation设置为显示动画的默认值 # %matplotlib notebook # %matplotlib inline # plt.rcParams["animation.html"] = "jshtml" # ani
import numpy as np import matplotlib.pyplot as plt from matplotlib import animation from IPython.display import HTML plt.rcParams[\'figure.figsize\'] = (5,3) plt.rcParams[\'figure.dpi\'] = 100 plt.rcParams[\'savefig.dpi\'] = 100 plt.rcParams["animation.html"] = "jshtml" # for matplotlib 2.1 and above, uses JavaScript #plt.rcParams["animation.html"] = "html5" # for matplotlib 2.0 and below, converts to x264 using ffmpeg video codec t = np.linspace(0,2*np.pi) x = np.sin(t) fig, ax = plt.subplots() ax.axis([0,2*np.pi,-1,1]) l, = ax.plot([],[]) def animate(i): l.set_data(t[:i], x[:i]) ani = animation.FuncAnimation(fig, animate, frames=len(t)) %matplotlib notebook ani
import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation fig, ax = plt.subplots() xdata, ydata = [], [] ln, = plt.plot([], [], \'ro\') def init(): ax.set_xlim(0, 2 * np.pi) ax.set_ylim(-1, 1) return ln, def update(frame): xdata.append(frame) ydata.append(np.sin(frame)) ln.set_data(xdata, ydata) print(frame) return ln, ani = FuncAnimation(fig, update, frames=np.linspace(0, 2 * np.pi, 128),init_func = init, blit = True) %matplotlib inline ani
import numpy as np import matplotlib.pyplot as plt from matplotlib import animation """ animation example 2 author: Kiterun """ fig, ax = plt.subplots() x = np.linspace(0, 2*np.pi, 200) y = np.sin(x) l = ax.plot(x, y) dot, = ax.plot([], [], \'ro\') def init(): ax.set_xlim(0, 2*np.pi) ax.set_ylim(-1, 1) return l def gen_dot(): for i in np.linspace(0, 2*np.pi, 200): newdot = [i, np.sin(i)] yield newdot def update_dot(newd): dot.set_data(newd[0], newd[1]) return dot, ani = animation.FuncAnimation(fig, update_dot, frames = gen_dot, interval = 100, init_func=init) plt.close() ani
from math import sin, cos import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt import matplotlib.animation as animation g = 9.8 leng = 1.0 b_const = 0.2 # no decay case: def pendulum_equations1(w, t, l): th, v = w dth = v dv = - g/l * sin(th) return dth, dv # the decay exist case: def pendulum_equations2(w, t, l, b): th, v = w dth = v dv = -b/l * v - g/l * sin(th) return dth, dv t = np.arange(0, 20, 0.1) track = odeint(pendulum_equations1, (1.0, 0), t, args=(leng,)) #track = odeint(pendulum_equations2, (1.0, 0), t, args=(leng, b_const)) xdata = [leng*sin(track[i, 0]) for i in range(len(track))] ydata = [-leng*cos(track[i, 0]) for i in range(len(track))] fig, ax = plt.subplots() ax.grid() line, = ax.plot([], [], \'o-\', lw=2) time_template = \'time = %.1fs\' time_text = ax.text(0.05, 0.9, \'\', transform=ax.transAxes) def init(): ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) time_text.set_text(\'\') return line, time_text def update(i): newx = [0, xdata[i]] newy = [0, ydata[i]] line.set_data(newx, newy) time_text.set_text(time_template %(0.1*i)) return line, time_text ani = animation.FuncAnimation(fig, update, range(1, len(xdata)), init_func=init, interval=50) #ani.save(\'single_pendulum_decay.gif\', writer=\'imagemagick\', fps=100) plt.close() ani
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig = plt.figure(figsize=(6, 6)) ax = plt.gca() ax.grid() ln1, = ax.plot([], [], \'-\', lw=2) ln2, = ax.plot([], [], \'-\', color=\'r\', lw=2) theta = np.linspace(0, 2*np.pi, 100) r_out = 1 r_in = 0.5 def init(): ax.set_xlim(-2, 2) ax.set_ylim(-2, 2) x_out = [r_out*np.cos(theta[i]) for i in range(len(theta))] y_out = [r_out*np.sin(theta[i]) for i in range(len(theta))] ln1.set_data(x_out, y_out) return ln1, def update(i): x_in = [(r_out-r_in)*np.cos(theta[i])+r_in*np.cos(theta[j]) for j in range(len(theta))] y_in = [(r_out-r_in)*np.sin(theta[i])+r_in*np.sin(theta[j]) for j in range(len(theta))] ln2.set_data(x_in, y_in) return ln2, ani = animation.FuncAnimation(fig, update, range(len(theta)), init_func=init, interval=30) plt.close() ani
mport numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 import matplotlib.animation as animation def Gen_RandLine(length, dims=2): """ Create a line using a random walk algorithm length is the number of points for the line. dims is the number of dimensions the line has. """ lineData = np.empty((dims, length)) lineData[:, 0] = np.random.rand(dims) # 初始化起点 for index in range(1, length): # scaling the random numbers by 0.1 so # movement is small compared to position. # subtraction by 0.5 is to change the range to [-0.5, 0.5] # to allow a line to move backwards. step = ((np.random.rand(dims) - 0.5) * 0.1) # 步长 # 下一步的位置 lineData[:, index] = lineData[:, index - 1] + step return lineData # 返回一个shape为(3,25)的数组,3维坐标25帧 def update_lines(num, dataLines, lines): for line, data in zip(lines, dataLines): # NOTE: there is no .set_data() for 3 dim data... line.set_data(data[0:2, :num]) line.set_3d_properties(data[2, :num]) return lines # Attaching 3D axis to the figure fig = plt.figure() ax = p3.Axes3D(fig) # Fifty lines of random 3-D lines (长为50的数组,每个元素为shape为3,25的ndarray,最后实际效果就是50条路径) data = [Gen_RandLine(25, 3) for index in range(50)] # Creating fifty line objects. # NOTE: Can\'t pass empty arrays into 3d version of plot() lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data] # 每条路径的起始点 # Setting the axes properties ax.set_xlim3d([0.0, 1.0]) ax.set_xlabel(\'X\') ax.set_ylim3d([0.0, 1.0]) ax.set_ylabel(\'Y\') ax.set_zlim3d([0.0, 1.0]) ax.set_zlabel(\'Z\') ax.set_title(\'3D Test\') # Creating the Animation object line_ani = animation.FuncAnimation(fig, update_lines, 25, fargs=(data, lines), interval=50, blit=False) plt.show()
ArtistAnimation
https://matplotlib.org/api/_as_gen/matplotlib.animation.ArtistAnimation.html
from matplotlib import animation, pyplot as plt import numpy as np data = np.random.random(20) fig,ax = plt.subplots(1,1) ax.plot(data) # draw background anim = animation.ArtistAnimation(fig, [[ax.scatter(x, y)] for x, y in enumerate(data)]) from IPython.display import HTML %matplotlib inline HTML(anim.to_jshtml()) # %matplotlib notebook # anim
图片的读取和保存
读取和显示
import matplotlib.pyplot as plt # plt 用于显示图片 import matplotlib.image as mpimg # mpimg 用于读取图片 import numpy as np lena = mpimg.imread(\'lena.png\') # 读取和代码处于同一目录下的 lena.png # 此时 lena 就已经是一个 np.array 了,可以对它进行任意处理 lena.shape #(512, 512, 3) plt.imshow(lena) # 显示图片 plt.axis(\'off\') # 不显示坐标轴 plt.show()
显示某个通道
# 显示图片的第一个通道 lena_1 = lena[:,:,0] plt.imshow(\'lena_1\') plt.show() # 此时会发现显示的是热量图,不是我们预想的灰度图,可以添加 cmap 参数,有如下几种添加方法: plt.imshow(\'lena_1\', cmap=\'Greys_r\') plt.show() img = plt.imshow(\'lena_1\') img.set_cmap(\'gray\') # \'hot\' 是热量图 plt.show()
将 RGB 转为灰度图
def rgb2gray(rgb): return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) gray = rgb2gray(lena) # 也可以用 plt.imshow(gray, cmap = plt.get_cmap(\'gray\')) plt.imshow(gray, cmap=\'Greys_r\') plt.axis(\'off\') plt.show()
对图像进行放缩
from scipy import misc lena_new_sz = misc.imresize(lena, 0.5) # 第二个参数如果是整数,则为百分比,如果是tuple,则为输出图像的尺寸 plt.imshow(lena_new_sz) plt.axis(\'off\') plt.show()
保存图像
5.1 保存 matplotlib 画出的图像。
该方法适用于保存任何 matplotlib 画出的图像,相当于一个 screencapture。
plt.imshow(lena_new_sz) plt.axis(\'off\') plt.savefig(\'lena_new_sz.png\')
5.2 将 array 保存为图像。
from scipy import misc misc.imsave(\'lena_new_sz.png\', lena_new_sz)
5.3 直接保存 array。
读取之后还是可以按照前面显示数组的方法对图像进行显示,这种方法完全不会对图像质量造成损失。
np.save(\'lena_new_sz\', lena_new_sz) # 会在保存的名字后面自动加上.npy img = np.load(\'lena_new_sz.npy\') # 读取前面保存的数组