# 太赞了！100个案例，Matplotlib 从入门到大神！

2020/11/25 17:00

Matplotlib 实操干货



import numpy as np

import matplotlib.pyplot as plt

plt.rcParams['text.usetex'] = True

plt.rcParams['font.size'] = 15

plt.rcParams['font.family'] = "serif"

tdir = 'in'

major = 5.0

minor = 3.0

plt.rcParams['xtick.direction'] = tdir

plt.rcParams['ytick.direction'] = tdir

plt.rcParams['xtick.major.size'] = major

plt.rcParams['xtick.minor.size'] = minor

plt.rcParams['ytick.major.size'] = major

plt.rcParams['ytick.minor.size'] = minor



## 01. 箱形图(Box plot)



N = 50

np.random.seed(100)

box1 = np.random.randn(N) * 2 + 1





plt.figure()

plt.boxplot(box1)



### 水平箱形图 (Horizontal box plot)



vert = False





N = 50

np.random.seed(140)

box1 = np.random.randn(N) * 2 + 1

plt.boxplot(box1, vert=False)





q1 = np.quantile(box1, .25)

q3 = np.quantile(box1, .75)

iqr = q3-q1

lower_boundary = q1 - 1.5 * iqr

upper_boundary = q3 + 1.5 * iqr

sort = np.sort(box1)





N = 50

np.random.seed(140)

box1 = np.random.randn(N) * 2 + 1

q1 = np.quantile(box1, .25)

q3 = np.quantile(box1, .75)

iqr = q3-q1

lower_boundary = q1 - 1.5 * iqr

upper_boundary = q3 + 1.5 * iqr

sort = np.sort(box1)

colors = ['#6b2983', '#5f82cb', '#00d6ff', '#e77ca3', '#93003a']

plt.figure(figsize=(9, 3.5))

plt.boxplot(box1, vert=False)

plt.scatter(box1, np.linspace(1.3, 1.3, box1.shape[0]), color = 'r', alpha = .4, label = 'random numbers')

plt.vlines(lower_boundary, ymin = 0.2, ymax=.65, alpha = .7, ls = '-.', color = 'k', label = 'Q1 - 1.5 x IQR')

plt.vlines(sort[0], ymin = 0.2, ymax = .65, ls = '-', lw = 1.25, color = colors[2], label = 'minimum')

plt.vlines(sort[-2], ymin = 0.2, ymax = .65, ls = '-', lw = 1.25, color = colors[3], label = 'maximum')

plt.vlines(sort[-1], ymin = 0.2, ymax = .65, ls = '-', lw = 1.25, color = colors[4], label = 'outliers')

plt.vlines(upper_boundary, ymin = 0.2, ymax=.65, alpha = .7, ls = '--', color = 'k', label = 'Q3 + 1.5 x IQR')

plt.annotate(np.round(lower_boundary, 2), xy = (lower_boundary, 0.7), ha = 'center', color = 'k')

plt.annotate(np.round(sort[0], 2), xy = (sort[0], 0.7), ha = 'center', color = colors[2])

plt.annotate(np.round(sort[-2], 2), xy = (sort[-2], 0.7), ha = 'center', color = colors[3])

plt.annotate(np.round(sort[-1], 2), xy = (sort[-1], 0.7), ha = 'center', color = colors[4])

plt.annotate(np.round(upper_boundary, 2), xy = (upper_boundary, 0.8), ha = 'center', color = 'k')

plt.legend(bbox_to_anchor = (1.0, 1.05))

plt.savefig('box4.png', dpi = 300, bbox_inches = 'tight', facecolor='w')





np.random.seed(1214)

data = [np.random.normal(0, std, 100) for std in range(10, 14)]



### 显示均值



plt.boxplot(data, showmeans=True)





plt.boxplot(data, showmeans=True, vert = False)





meanline=True





showbox=False





patch_artist=True





colors = ['royalblue', 'lightblue', 'lightgreen', 'pink']

for patch, color in zip(box['boxes'], colors):

    patch.set_facecolor(color)





np.random.seed(123)

all_data = [np.random.normal(0, std, 100) for std in range(10, 14)]

box = plt.boxplot(all_data, notch=False, patch_artist=True)

colors = ['royalblue', 'lightblue', 'lightgreen', 'pink']

for patch, color in zip(box['boxes'], colors):

    patch.set_facecolor(color)

plt.ylim(-50, 50)



### 激活缺口(Activate notch)



notch=True





np.random.seed(123)

all_data = [np.random.normal(0, std, 100) for std in range(10, 14)]

box = plt.boxplot(all_data, notch=True, patch_artist=True)

colors = ['royalblue', 'lightblue', 'lightgreen', 'pink']

for patch, color in zip(box['boxes'], colors):

    patch.set_facecolor(color)

plt.ylim(-50, 50)



## 02. 小提琴图(Violin plot)



N = 50

np.random.seed(140)

viol = np.random.randn(N) * 2 + 1

plt.figure()

plt.violinplot(viol)





vert=False





showmeans=True, showmedians=True





violin_parts = plt.violinplot(data, showmedians=True, 

                              showmeans=True)





vmedian = violin_parts['cmedians']

vmedian.set_edgecolor('r')

vmean = violin_parts['cmeans']

vmean.set_edgecolor('k')

vbars = violin_parts['cbars']

vbars.set_edgecolor('k')

vmax = violin_parts['cmaxes']

vmax.set_edgecolor('darkorange')

vmin = violin_parts['cmins']

vmin.set_edgecolor('darkorange')





np.random.seed(1214)

data = [np.random.normal(0, std, 100) for std in range(10, 14)]

plt.figure(figsize = (10, 6))

violin_parts = plt.violinplot(data, showmedians=True, 

                              showmeans=True)

vbars = violin_parts['cbars']

vbars.set_edgecolor('k')

vmedian = violin_parts['cmedians']

vmedian.set_edgecolor('r')

vmean = violin_parts['cmeans']

vmean.set_edgecolor('k')

vmax = violin_parts['cmaxes']

vmax.set_edgecolor('darkorange')

vmin = violin_parts['cmins']

vmin.set_edgecolor('darkorange')





for vp in violin_parts['bodies']:

    vp.set_facecolor('orange')

    vp.set_edgecolor('k')

    vp.set_linewidth(3)





np.random.seed(1214)

data = [np.random.normal(0, std, 100) for std in range(10, 14)]

plt.figure(figsize = (10, 6))

violin_parts = plt.violinplot(data, widths=0.9, showmedians=True)

for vp in violin_parts['bodies']:

    vp.set_facecolor('orange')

    vp.set_edgecolor('k')

    vp.set_linewidth(3)





np.random.seed(1214)

data = [np.random.normal(0, std, 100) for std in range(10, 14)]

# Create violin plot objects:

plt.figure(figsize=(10, 6))

violin_parts=plt.violinplot(data, showmedians=True, showmeans=True)

# Make the violin body blue with a red border:

for vp in violin_parts['bodies']:

    vp.set_facecolor('royalblue')

    vp.set_edgecolor('k')

    vp.set_linewidth(2)

    vp.set_alpha(.8)

colors = ['k', 'red', 'red', 'w', 'k']

part = ['cbars','cmins','cmaxes','cmeans','cmedians']

for i in range(len(part)):

    vp = violin_parts[part[i]]

    vp.set_edgecolor(colors[i])

    vp.set_linewidth(2)



## 03. 饼图（Pie chart）



labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'

numbers = [15, 30, 45, 10]





plt.pie(numbers)





labels = labels





autopct='%1.1f%%'





labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'

sizes = [15, 30, 45, 10]

plt.figure()

plt.pie(sizes, labels = labels, autopct='%1.1f%%')





startangle=90





labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'

sizes = [15, 30, 45, 10]

explode1 = (0, 0.1, 0, 0)

explode2 = (0, 0, 0.1, 0)

plt.figure(figsize=(10, 10))

plt.subplot(121)

plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)

plt.title('Startangle = 90$^\circ$')plt.subplot(122)

plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=180)

plt.title('Startangle = 180$^\circ$')





labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'

sizes = [15, 30, 45, 10]

explode1 = (0, 0.1, 0, 0)

explode2 = (0, 0, 0.1, 0)

plt.figure(figsize=(10, 10))plt.subplot(121)

plt.pie(sizes, explode=explode1, labels=labels, 

        autopct='%1.1f%%', startangle=90)plt.subplot(122)

plt.pie(sizes, explode=explode2, labels=labels, 

        autopct='%1.1f%%', startangle=180)



### 在饼图中应用不同的样式



textprops={'color':"w"}





plt.legend(labels, bbox_to_anchor = (1., .95),  title="Labels Name")





labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'

sizes = [15, 30, 45, 10]

explode = (0, 0.05, 0, 0)

plt.figure(figsize=(7, 7))

plt.pie(sizes, autopct='%1.1f%%', textprops={'color':"w"}, 

        explode = explode, startangle = 90)



### 饼图中设置阴影



shadow=True



1. 如果您使用的是 Jupyter，则可以通过右键单击该图来手动保存饼图。然后，单击“将图像另存为”，如 图22 所示:

1. 另一种选择是将白色描边添加为前景。要应用它，您需要使用以下代码从 Matplotlib 导入 path_effects 。



import matplotlib.patheffects as path_effects





patches, texts, autotexts = plt.pie(sizes, autopct='%1.1f%%', 

                                    textprops={'color':"w"}, 

                                    explode = explode, 

                                    startangle = 90, shadow=True)





for patch in patches:

    patch.set_path_effects([path_effects.Stroke(linewidth=2.5, 

                                                foreground = 'w')])





labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'

sizes = [15, 30, 45, 10]

explode = (0, 0.05, 0, 0)

plt.figure(figsize=(7, 7), facecolor = 'w')

patches, texts, autotexts = plt.pie(sizes, autopct='%1.1f%%', 

                                    textprops={'color':"w"}, 

                                    explode = explode, 

                                    startangle = 90, shadow=True)

for patch in patches:

    patch.set_path_effects([path_effects.Stroke(linewidth=2.5, 

                                                foreground = 'w')])

plt.legend(labels, bbox_to_anchor = (1., .95),  title="Labels Name")



### 环形图（Doughnut chart）



size = 0.3

vals = np.array([[60.], [37.], [29.]])cmap = plt.get_cmap("tab20c")

outer_colors = cmap(np.arange(3)*4)

inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))





plt.figure(figsize=(10,10))

plt.pie(vals.sum(axis=1), radius=1, colors=outer_colors,

       wedgeprops=dict(width=size, edgecolor='w'))





vals = np.array([[60.], [37.], [29.]])

plt.figure(figsize=(10,10))plt.subplot(121)

plt.pie(vals.sum(axis=1), radius=1, colors=outer_colors,

       wedgeprops=dict(width=.3, edgecolor='w'))

plt.title('Size = 0.3')plt.subplot(122)

plt.pie(vals.sum(axis=1), radius=1, colors=outer_colors,

       wedgeprops=dict(width=.5, edgecolor='w'))

plt.title('Size = 0.5')





plt.figure(figsize=(10, 10))

size = 0.3

vals = np.array([[60., 32.], [37., 40.], [29., 10.]])

cmap = plt.get_cmap("tab20c")

outer_colors = cmap(np.arange(3)*4)

inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))

plt.pie(vals.sum(axis=1), radius=1, colors=outer_colors,

       wedgeprops=dict(width=size, edgecolor='w'))

plt.pie(vals.flatten(), radius=1-size, colors=inner_colors,

       wedgeprops=dict(width=size, edgecolor='w'))





fig, ax = plt.subplots(figsize=(10, 4.5), subplot_kw=dict(aspect="equal"))

recipe = ["225 g flour",

          "90 g sugar",

          "1 egg",

          "60 g butter",

          "100 ml milk",

          "1/2 package of yeast"]

data = [225, 90, 50, 60, 100, 5]

wedges, texts = ax.pie(data, wedgeprops=dict(width=0.5), startangle=-40)

bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)

kw = dict(arrowprops=dict(arrowstyle="-"),

          bbox=bbox_props, zorder=0, va="center")

for i, p in enumerate(wedges):

    ang = (p.theta2 - p.theta1)/2. + p.theta1

    y = np.sin(np.deg2rad(ang))

    x = np.cos(np.deg2rad(ang))

    horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]

    connectionstyle = "angle,angleA=0,angleB={}".format(ang)

    kw["arrowprops"].update({"connectionstyle": connectionstyle})

    ax.annotate(recipe[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),

                horizontalalignment=horizontalalignment, **kw)

ax.set_title("Matplotlib bakery: A donut")



## 04. 极坐标图（Polar chart）



projection='polar'





r = np.linspace(0, 2, 100)

theta = 2 * np.pi * r

fig = plt.figure(figsize=(13, 4))

ax1 = plt.subplot(121, projection='polar')

ax1.scatter(theta, r, label = 'Polar Projection', s = 10)

ax1.legend(bbox_to_anchor = (.85, 1.35))

ax2 = plt.subplot(122)

ax2.scatter(theta, r, label = 'Planar Projection', s = 10)

ax2.legend(bbox_to_anchor = (0.85, 1.35))

ax2.set_xlabel('R')

ax2.set_ylabel(r'$\theta$')





r = np.linspace(0, 2, 100)

theta = 2 * np.pi * r

fig = plt.figure(figsize=(13, 4))

ax1 = plt.subplot(121, projection='polar')

ax1.plot(theta, r, label = 'Polar Projection', ls = '--', color = 'r')

ax1.legend(bbox_to_anchor = (.85, 1.35))

ax2 = plt.subplot(122)

ax2.plot(theta, r, label = 'Planar Projection')

ax2.legend(bbox_to_anchor = (.85, 1.35))





np.random.seed(10130)

N = 20

theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)

radii = 10 * np.random.rand(N)

width = np.random.rand(N) * .8 - .1

colors = plt.cm.Spectral(radii / 10)





plt.figure(figsize=(7, 7))

ax = plt.subplot(111, projection='polar')

ax.bar(theta, radii, width=width, bottom=0.0,

       color=colors, alpha=0.5)



https://matplotlib.org/3.1.0/gallery/misc/logos2.html

## 05. 地理投影（Geographic projection）



N = 100

np.random.seed(157)

long = np.random.random(N) * 360 - 180

lat = np.random.random(N) * 180 - 90



To visualize it in the Aitoff projection, you can use this code

Aitoff 投影的代码如下：



plt.figure(figsize=(12, 7))

plt.subplot(111, projection="aitoff")

plt.scatter(long, lat, marker = '*', color = 'red', s = 40)

plt.title("Aitoff")

plt.grid(True)



Hammer 投影的代码如下：



plt.figure(figsize=(12, 7))

plt.subplot(111, projection="hammer")

plt.scatter(long, lat, marker = '*', color = 'red', s = 40)

plt.title("Hammer")

plt.grid(True)



Hammer 投影中所示的 long 和 lat 变量的单位是度。上面的代码将生成一个图形，如 图34 所示:

Aitoff 投影

https://en.wikipedia.org/wiki/Aitoff_projection

Hammer 投影

https://en.wikipedia.org/wiki/Hammer_projection



N = 100

np.random.seed(157)

long = np.random.random(N) * 2 * np.pi  - np.pi

lat = np.random.random(N) * np.pi - (np.pi / 2)



Hammer 投影的代码如下：



plt.figure(figsize=(12, 7))

plt.subplot(111, projection="mollweide")

plt.scatter(long, lat, marker = '*', color = 'red', s = 40)

plt.title("Mollweide")

plt.grid(True)



Lambert 投影的图示如 图36 所示：



N = 100

np.random.seed(157)

long = np.random.random(N) * 2 * np.pi  - np.pi

lat = np.random.random(N) * np.pi - (np.pi / 2)

plt.figure(figsize=(12, 12))

plt.subplot(111, projection="lambert")

plt.scatter(long, lat, marker = '*', color = 'red', s = 40)

plt.title("Lambert")

plt.grid(True)



## 06. 3D图（3D plot）



projection = '3d'



3D 投影将为您提供如 图37 所示的结果:



N = 250

np.random.seed(124)

x = 15 * np.random.random(N)

y = np.sin(x) + 0.25 * np.random.random(N)

z = np.cos(x) + 0.25 * np.random.random(N)





plt.figure(figsize=(9, 6))

ax = plt.axes(projection = '3d')

ax.scatter3D(x, y, z, color = 'r')

ax.set_xlabel('x', fontsize = 20, labelpad = 20)

ax.set_ylabel('y', fontsize = 20, labelpad = 20)

ax.set_zlabel('z', fontsize = 20, labelpad = 20)



3D 图的结果如 图38 所示：



ax.set_box_aspect((2., 1.5, 1.2))



### 3D线形图（3D plotline）

3D线形图如 图40 所示：



N = 100

np.random.seed(124)

xline = np.linspace(0, 15, N)

yline = np.sin(xline) 

zline = np.cos(xline)

fig = plt.figure(figsize=(9, 6))

ax = plt.axes(projection = '3d')

ax.plot3D(xline, yline, zline)

ax.set_xlabel('x')

ax.set_ylabel('y')

ax.set_zlabel('z')

ax.set_box_aspect((2, 1.5, 1.2))





ax.view_init(10, 180)



view_init 中的第一个参数是仰角，第二个参数是方位角，可以看到不同角度的不同表示形式，如 图41 所示：

### 三角3D曲面（Triangular 3D surfaces）



ax.plot_trisurf()





N = 2000

np.random.seed(124)

r = 2 * np.pi * np.random.random(N)

theta = 20 * np.pi * np.random.random(N)

xdata = np.ravel(r * np.sin(theta))

ydata = np.ravel(r * np.cos(theta))

zdata = np.sin(xdata) + np.cos(ydata)





N = 2000

np.random.seed(124)

r = 2 * np.pi * np.random.random(N)

theta = 20 * np.pi * np.random.random(N)

xdata = np.ravel(r * np.sin(theta))

ydata = np.ravel(r * np.cos(theta))

zdata = np.sin(xdata) + np.cos(ydata)

fig = plt.figure(figsize=(15, 6))

plt.subplots_adjust(wspace=0)

ax1 = plt.subplot(121, projection = '3d')

ax1.plot_trisurf(xdata, ydata, zdata, cmap = 'inferno')

ax1.set_xlabel('x')

ax1.set_ylabel('y')

ax1.set_zlabel('z')

ax1.view_init(40, 100)

ax1.set_box_aspect((4.5, 4.5, 1.5))

ax1.set_title('Elevation = 40$^\circ$, Azimuth = 100$^\circ$')

ax2 = plt.subplot(122, projection = '3d')

ax2.plot_trisurf(xdata, ydata, zdata, cmap = 'inferno')

ax2.set_xlabel('x')

ax2.set_ylabel('y')

ax2.set_zlabel('z')

ax2.view_init(20, 100)

ax2.set_box_aspect((4.5, 4.5, 1.5))

ax2.set_title('Elevation = 20$^\circ$, Azimuth = 100$^\circ$')



### 3D等高线图（3D contour plot）

Matplotlib 提供 3D等高线图，可以使用下面的代码创建：



ax.contour3D()





N = 100

np.random.seed(3124)

x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)





fig = plt.figure(figsize=(9, 6))

ax = plt.axes(projection = '3d')

ax.contour3D(X, Y, Z, cmap = 'Spectral')





N = 100

np.random.seed(3124)

x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)

fig = plt.figure(figsize=(9, 6))

ax = plt.axes(projection = '3d')

ax.contour3D(X, Y, Z, cmap = 'Spectral')

ax.set_xlabel('x')

ax.set_ylabel('y')

ax.set_zlabel('z')

ax.set_box_aspect((2, 2, 1))

ax.view_init(60, 100)

ax.set_title('Contour counts = Default, elevation = 60, azimuth = 100')





ax.contour3D(X, Y, Z, 256, cmap = 'Spectral')





N = 100

np.random.seed(3124)

x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)

fig = plt.figure(figsize=(20, 6))

ax = plt.axes(projection = '3d')

p = ax.contour3D(X, Y, Z, 256, cmap = 'Spectral')

ax.set_xlabel('x')

ax.set_ylabel('y')

ax.set_zlabel('z')

ax.set_box_aspect((3, 3, 1))

ax.view_init(60, 100)

plt.colorbar(p)

ax.set_title('Contour counts = 256, elevation = 60, azimuth = 100')





plt.colorbar()



### 3D等高线图的一些 bugs

ax.contourf 中的 contourf 表示填充轮廓。因此，可以在 图48 中看到 ax.contour（） 和 ax.contourf（） 之间的区别。 ax.contour 具有与 ax.contour3D（） 类似的默认轮廓计数，为 7 个计数。但是， ax.contourf（） 的计数不同，为8。您可以使用此代码重现 图48 :



N = 100

np.random.seed(3124)

x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)

plt.figure(figsize=(14, 6))

ax1 = plt.subplot(121, projection = '3d')

ax1.contour(X, Y, Z, cmap = 'Spectral')

ax1.set_xlabel('x')

ax1.set_ylabel('y')

ax1.set_zlabel('z')

ax1.set_box_aspect((3, 3, 1))

ax1.view_init(10, 100)

ax1.set_title('Contour Default, elevation = 10, azimuth = 100')ax2 = plt.subplot(122, projection = '3d')

ax2.contourf(X, Y, Z, cmap = 'Spectral')

ax2.set_xlabel('x')

ax2.set_ylabel('y')

ax2.set_zlabel('z')

ax2.set_box_aspect((3, 3, 1))

ax2.view_init(10, 100)

ax2.set_title('Contourf Default, elevation = 10, azimuth = 100')



### 线框图 （Wireframe plot）



ax.plot_wireframe()





N = 100

np.random.seed(3124)

x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)





N = 100

np.random.seed(3124)

x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)

fig = plt.figure(figsize=(10, 10))

ax = plt.axes(projection = '3d')

ax.plot_wireframe(X, Y, Z, color = 'k', alpha = .2)





N = 100

np.random.seed(3124)

x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)

fig = plt.figure(figsize=(9, 6))

ax = plt.axes(projection = '3d')

# 3d contour plot

ax.plot_wireframe(X, Y, Z, 5, color = 'k', alpha = .2)

ax.set_xlabel('x')

ax.set_ylabel('y')

ax.set_zlabel('z')

ax.set_box_aspect((2, 2, 1))

ax.view_init(60, 100)

ax.set_title('Wireframe counts = 5, elevation = 60, azimuth = 100')



### 3D表面图 （3D surface plot）

3D表面图 （3D surface plot）的代码设置如下：



ax.plot_surface()



3D表面图 （3D surface plot）的自定义设置如 图53：



N = 100

np.random.seed(3124)

x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)

fig = plt.figure(figsize=(8, 8))ax = plt.axes(projection = '3d')

# 3d contour plot

ax.plot_surface(X, Y, Z, )

ax.set_xlabel('x')

ax.set_ylabel('y')

ax.set_zlabel('z')

ax.set_box_aspect((2, 2, 1))

ax.view_init(10, 100)

ax.set_title('Plot surface Default, elevation = 10, azimuth = 100')





rstride = 1, cstride = 1





N = 200

np.random.seed(3124)

x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)

fig = plt.figure(figsize=(14, 6))

ax1 = plt.subplot(121, projection = '3d')# 3d contour plot

ax1.plot_surface(X, Y, Z,  cmap = 'Spectral')

ax1.set_xlabel('x')

ax1.set_ylabel('y')

ax1.set_zlabel('z')

ax1.set_box_aspect((2, 2, 1))

ax1.view_init(60, 100)

ax1.set_title('Plot surface rstride = cstride = default, \n elevation = 60, azimuth = 100')

ax2 = plt.subplot(122, projection = '3d')# 3d contour plot

ax2.plot_surface(X, Y, Z,  cmap = 'Spectral', rstride = 1, cstride = 1)

ax2.set_xlabel('x')

ax2.set_ylabel('y')

ax2.set_zlabel('z')

ax2.set_box_aspect((2, 2, 1))

ax2.view_init(60, 100)

ax2.set_title('Plot surface rstride = cstride = 1, \n elevation = 60, azimuth = 100')



### 在Matplotlib中创建球体



u = np.linspace(0, 2 * np.pi, 100)

v = np.linspace(0, np.pi, 100)

x = 10 * np.outer(np.cos(u), np.sin(v))

y = 10 * np.outer(np.sin(u), np.sin(v))

z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))

plt.figure(figsize=(10, 10))

ax = plt.subplot(projection = '3d')

ax.plot_surface(x, y, z, cmap = 'inferno')





u = np.linspace(0, 2 * np.pi, 100)

v = np.linspace(0, np.pi, 100)

x = 10 * np.outer(np.cos(u), np.sin(v))

y = 10 * np.outer(np.sin(u), np.sin(v))

z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))

rows = 2

columns = 2

grid = plt.GridSpec(rows, columns, wspace = .2, hspace = .2)

elev = np.arange(0, 40, 10)

azim = np.arange(0, 200, 50)

plt.figure(figsize=(12, 12))

for i in range(rows * columns):

    ax = plt.subplot(grid[i], projection = '3d')

    ax.plot_surface(x, y, z, cmap = 'inferno')

    ax.view_init(elev[i], azim[i])

    ax.set_title('Elevation = ' + str(elev[i]) + ', Azimuth = ' + str(azim[i]))



## 07. 2D等高线图（2D Contour plot）



plt.contour()





N = 100

np.random.seed(100)

x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)





N = 100

np.random.seed(100)

x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)

plt.figure(figsize=(7, 5))

plt.contour(X, Y, Z)

plt.title('Contour 2D Default', pad = 10)





N = 100

np.random.seed(100)

x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)

plt.figure(figsize=(15, 5))

plt.subplot(121)

plt.contour(X, Y, Z, 256)

plt.title('Contour 2D counts = 256, cmap = viridis', pad = 10)

plt.colorbar()

plt.subplot(122)

plt.contour(X, Y, Z, 256, cmap = 'Spectral')

plt.colorbar()

plt.title('Contour 2D counts = 256, cmap = Spectral', pad = 10)





N = 100

np.random.seed(100)x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)**3

plt.figure(figsize=(7, 5))

plt.contourf(X, Y, Z, cmap = 'Spectral')

plt.colorbar()

plt.title('Contourf 2D Default', pad = 10)





N = 100

np.random.seed(100)

x = np.linspace(-2, 2, N) + np.random.random(N)

y = np.linspace(-2, 2, N) + np.random.random(N)

X, Y = np.meshgrid(x, y)

Z = np.sin(X) + np.cos(Y)**3

plt.figure(figsize=(15, 5))

plt.subplot(121)

plt.contourf(X, Y, Z, 50, cmap = 'inferno')

plt.colorbar()

plt.title('Contourf 2D counts = 50', pad = 10)plt.subplot(122)

plt.contourf(X, Y, Z, 200, cmap = 'inferno')

plt.colorbar()

plt.title('Contourf 2D counts = 200', pad = 10)



## 总结

https://towardsdatascience.com/python-data-visualization-with-matplotlib-part-2-66f1307d42fb

下载1：leetcode 开源书在「AI算法与图像处理」公众号后台回复：leetcode，即可下载。每题都 runtime beats 100% 的开源好书，你值得拥有！

下载2 CVPR2020

在「AI算法与图像处理」公众号后台回复：

CVPR2020

，即可下载1467篇CVPR 2020论文

个人微信（如果没有备注不拉群！）

请注明：

地区+学校/企业+研究方向+昵称





‍



0
0 收藏

0 评论
0 收藏
0