首页 技术 正文
技术 2022年11月16日
0 收藏 407 点赞 4,056 浏览 5931 个字

一、引入


import matplotlib as mpl

import matplotlib.pyplot as plt

二、配置


1、画图接口

Matplotlib 有两种画图接口:

(1)一个是便捷的 MATLAB 风格接口

(2)功能更强大的面向对象接口【推荐,下文都以这个为例】

在面向对象接口中,画图函数不再受到当前“活动”图形或坐标轴的限制,而变成了显式的 Figure 和 Axes 的方法(一个Figure画布下可以有多个Axes子图)。

2、静态 or 交互

%matplotlib notebook 会在 Notebook 中启动交互式图形

%matplotlib inline 会在 Notebook 中启动静态图形

下文统一使用%matplotbib inline。

3、样式表

默认是经典(classic)的 Matplotlib 风格:

plt.style.use('classic')

更多风格:

plt.style.available# ['_classic_test',
'bmh',
'classic',
'dark_background',
'fast',
'fivethirtyeight',
'ggplot',
'grayscale',
'seaborn-bright',
'seaborn-colorblind',
'seaborn-dark-palette',
'seaborn-dark',
'seaborn-darkgrid',
'seaborn-deep',
'seaborn-muted',
'seaborn-notebook',
'seaborn-paper',
'seaborn-pastel',
'seaborn-poster',
'seaborn-talk',
'seaborn-ticks',
'seaborn-white',
'seaborn-whitegrid',
'seaborn',
'Solarize_Light2',
'tableau-colorblind10']

也可自定义样式文件:

.mplstyle

4、导出

fig.savefig('my_figure.png')

支持的格式可以通过这个查看:

fig.canvas.get_supported_filetypes()

二、用法

1、线形图

fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 1000)
ax.plot(x, np.cos(x),color='blue',linestyle='dotted',label='cos(x)');
ax.plot(x, np.sin(x),color='0.9',label='sin(x)');


# ----- 调整线条 -----# color - 调整线条的颜色ax.plot(x, np.sin(x - 0), color='blue') # 标准颜色名称
ax.plot(x, np.sin(x - 1), color='g') # 缩写颜色代码(rgbcmyk)
ax.plot(x, np.sin(x - 2), color='0.75') # 范围在0~1的灰度值
ax.plot(x, np.sin(x - 3), color='#FFDD44') # 十六进制(RRGGBB,00~FF)
ax.plot(x, np.sin(x - 4), color=(1.0,0.2,0.3)) # RGB元组,范围在0~1
ax.plot(x, np.sin(x - 5), color='chartreuse'); # HTML颜色名称# linestyle - 调整线条的风格ax.plot(x, x + 0, linestyle='solid')
ax.plot(x, x + 1, linestyle='dashed')
ax.plot(x, x + 2, linestyle='dashdot')
ax.plot(x, x + 3, linestyle='dotted');
# 你可以用下面的简写形式
ax.plot(x, x + 4, linestyle='-') # 实线
ax.plot(x, x + 5, linestyle='--') # 虚线
ax.plot(x, x + 6, linestyle='-.') # 点划线
ax.plot(x, x + 7, linestyle=':'); # 实点线
# ----- 调整坐标轴 -----# 坐标轴上下限
ax.xlim(-1, 11)
ax.ylim(-1.5, 1.5);
ax.ylim(1.5, -1.5);# 坐标逆序
ax.axis([-1, 11, -1.5, 1.5]);# 紧凑模式
ax.axis('tight');# 横纵坐标 1:1
ax.axis('equal');# ----- 调整标题 -----# 设置图形标题、横纵坐标标题
ax.title("A Sine Curve")
ax.xlabel("x")
ax.ylabel("sin(x)"); # ----- 图例(跟 label 属性挂钩) -----ax.legend()# 详细属性请查文档
ax.legend(loc='upper left', frameon=True, ncol=2, fancybox=True, framealpha=1, shadow=True, borderpad=1)
# 选择图例显示的元素
# 略# 在图例中显示不同尺寸的点
# 略# 同时显示多个图例
# 略

2、散点图(scatter plot)

(1)方法一:

跟上面线形图的区别在于 ax.plot() 的第三个参数传了个字符。

fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 30)
ax.plot(x, np.sin(x), 'o', color='black');
# 第三个参数可能值:['o', '.', ',', 'x', '+', 'v', '^', '<', '>', 's', 'd']

(2)方法二:plt.scatter

取舍:面对大型数据集时,plt.plot 方法比 plt.scatter 方法性能要好。

3、误差线

fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 50)
dy = np.linspace(0, 1, 50)
y = np.sin(x) # 1、基本误差线
ax.errorbar(x, y, yerr=dy, fmt='o', color='black', ecolor='lightgray', elinewidth=3, capsize=0);
# 经验:让误差线的颜色比数据点的颜色浅一点效果会非常好,尤其是在那些比较密集的图形中# 2、连续误差线

4、密度图与等高线图

fig = plt.figure()
ax = plt.axes()# 1、用 plt.contour 画等高线图def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)
X, Y = np.meshgrid(x, y)Z = f(X, Y)
ax.contour(X, Y, Z, colors='black');
# 当图形中只使用一种颜色时,默认使用虚线表示负数,使用实线表示正数。# 单色(深浅)
ax.contour(X, Y, Z, 20, colors='black');
# 双色(红灰)(RdGy = Red-Gray = 红灰)
ax.contour(X, Y, Z, 20, cmap='RdGy');# 见下图1# 2、用 plt.contourf 画带有填充色的等高线图
ax.contourf(X, Y, Z, 20, cmap='RdGy');# 见下图2# 3、更复杂的图形用 plt.imshow
# 略# plt.contour、plt.contourf 与 plt.imshow 这三个函数组合起来之后,就打开了用二维图画三维数据的无尽可能。

5、频次直方图

(1)一维
fig = plt.figure()
ax = plt.axes()data = np.random.randn(1000) # 1、hist 画单个频次直方图
ax.hist(data, bins=30, normed=11, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none');# 2、hist 画多个频次直方图 (见下图)
x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random.normal(-2, 1, 1000)
x3 = np.random.normal(3, 2, 1000)
kwargs = dict(histtype='stepfilled', alpha=0.3, normed=True, bins=40)
ax.hist(x1, **kwargs)
ax.hist(x2, **kwargs)
ax.hist(x3, **kwargs);# 3、只计算数值结果不画图
counts, bin_edges = np.histogram(data, bins=5)
print(counts, bin_edges)
# [ 64 372 419 138 7] [-2.71435952 -1.43623111 -0.1581027 1.12002572 2.39815413 3.67628254]

(2)二维
fig = plt.figure()
ax = plt.axes()mean = [0, 0]
cov = [[1, 1], [1, 2]]
# 用多元高斯分布(multivariate Gaussian distribution)生成 x 轴与 y 轴的样本数据:
x, y = np.random.multivariate_normal(mean, cov, 10000).T# 1、plt.hist2d:二维频次直方图
plt.hist2d(x, y, bins=30, cmap='Blues')# 看下图
# plt.hexbin:矩形划分 -> 六边形划分
# ax.hexbin(x, y, gridsize=30, cmap='Blues')
cb = plt.colorbar(label='count in bin')# 2、平滑版本的二维频次直方图 - 核密度估计(kernel density estimation,KDE)
略# 3、只计算数值结果不画图
counts, xedges, yedges = np.histogram2d(x, y, bins=30)

6、文字与注释

(1)文字
# 拿前面第一个线形图的做例子:
fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 1000)
ax.plot(x, np.cos(x),color='blue',linestyle='dotted',label='cos(x)');
ax.plot(x, np.sin(x),color='0.9',label='sin(x)');# ax.text() 在图上增加文字标签
style = dict(size=10, color='gray')
ax.text(1, 0.1, "111", ha='center',**style)
ax.text(5, 0.5, "222", ha='center', **style)
ax.text(10, 0.8, "333", ha='center', **style)

ax.text() 的 transform 有三种不同的坐标系:

# 1、transData 坐标用x 轴与y 轴的标签作为数据坐标。
ax.text(1, 1, ". Data: (1, 1)", transform=ax.transData)# 2、transAxes 坐标以坐标轴(图中白色矩形)左下角的位置为原点,按坐标轴尺寸的比例呈现坐标。
ax.text(0.5, 0.1, ". Axes: (0.5, 0.1)", transform=ax.transAxes)# 3、transFigure 坐标与之类似,不过是以图形(图中灰色矩形)左下角的位置为原点,按图形尺寸的比例呈现坐标。
ax.text(0.2, 0.2, ". Figure: (0.2, 0.2)", transform=fig.transFigure);# 假如你改变了坐标轴上下限,那么只有transData 坐标会受影响,其他坐标系都不变!

(2)箭头
# 拿前面第一个线形图的做例子:
fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 1000)
ax.plot(x, np.cos(x),color='blue',linestyle='dotted',label='cos(x)');
ax.plot(x, np.sin(x),color='0.9',label='sin(x)');# ax.text() 在图上增加文字标签
ax.annotate('local maximum', xy=(1, 0.3), xytext=(3, 0.5), arrowprops=dict(facecolor='black', shrink=0.05))

7、三维图

# ax.plot3D - 三维线图
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline, 'gray')# ax.scatter3D - 三维散点图
zdata = 15 * np.random.random(100)
xdata = np.sin(zdata) + 0.1 * np.random.randn(100)
ydata = np.cos(zdata) + 0.1 * np.random.randn(100)
ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap='Greens');# 等高线、线框图、曲面图 区别

8、地图

需要用到第三方库:conda install basemap

9、更多功能

# 配置颜色条
# 略# 多子图
# 略# 自定义坐标轴刻度
# 略

https://matplotlib.org/gallery.html 可以看到更多的图形 demo 和配套代码

三、其他画图方法


1、Seaborn

第三方的 Seaborn 在 Matplotlib 的基础上开发了一套 API,为默认的图形样式和颜色设置提供了理智的选择,为常用的统计图形定义了许多简单的高级函数,并与 Pandas DataFrame 的功能有机结合。


2、pandas DataFrame 自带画图功能

df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
print(df)
ax = df.plot.bar(x='lab', y='val', rot=0)# 赋值给 ax 是为了不让输出 df.plot.bar 这个冗余信息


参考资料

《Python 数据科学手册》

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,996
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,510
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,353
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,137
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848