Drawing 3D charts and statistical maps

1. Drawing 3D charts using mplot3d

1.1 Mplot3d overview

1
2
3
4
5
6
7
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)

plt.show()

Axes3D() function

1
2
3
4
5
6
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

plt.show()

add_subplot() function

1.2 Draw common 3D charts

1
2
3
4
5
6
7
8
9
10
11
12
13
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Data
X, Y, Z = axes3d.get_test_data(0.05)

# Draw 3D Wireframes
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

plt.show()

Draw wireframe

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np

# Data
x1 = np.arange(-5, 5, 0.25)
y1 = np.arange(-5, 5, 0.25)
x1, y1 = np.meshgrid(x1, y1)
r1 = np.sqrt(x1 ** 2 + y1 ** 2)
z1 = np.sin(r1)

# Draw
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plot surface
ax.plot_surface(x1, y1, z1, cmap=cm.coolwarm, linewidth=0, antialiased=False)

# Set the range, position, format of the z-axis scale
ax.set_zlim(-1.01, 1.01)

plt.show()

Draw surface

1.3 Demo1: Stars in three-dimensional space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import numpy as np
import matplotlib.pyplot as plt

# Support Chinese
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

# Data
x = np.random.randint(0, 40, 30)
y = np.random.randint(0, 40, 30)
z = np.random.randint(0, 40, 30)

# Create a plot area of the 3D coordinate system and draw a 3D scatter plot in this area
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

for xx, yy, zz in zip(x, y, z):
color = 'y'
if 10 < zz < 20:
color = '#C71585'
elif zz >= 20:
color = '#008B8B'
ax.scatter(xx, yy, zz, c=color, marker='*',
s=160, linewidth=1, edgecolor='black')

# Set label and title
ax.set_xlabel('x轴')
ax.set_ylabel('y轴')
ax.set_zlabel('z轴')
ax.set_title('3D散点图', fontproperties='simhei', fontsize=14)

plt.tight_layout()
plt.show()

Stars in three-dimensional space

2. Using animation to make a dynamic diagram

2.1 Animation overview

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

x = np.arange(0, 2 * np.pi, 0.01)
fig, ax = plt.subplots()
line, = ax.plot(x, np.sin(x))


# define animate
def animate(i):
line.set_ydata(np.sin(x + i / 10))
return line


# define init func
def init():
line.set_ydata(np.sin(x))


ani = FuncAnimation(fig=fig, func=animate, frames=100,
init_func=init, interval=20, blit=False)

plt.show()

FuncAnimation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation

# Data
x = np.arange(0, 2 * np.pi, 0.01)
fig, ax = plt.subplots()

# Use array storage
arr = []
for i in range(5):
line = ax.plot(x, np.sin(x + i))
arr.append(line)

ani = ArtistAnimation(fig=fig, artists=arr, repeat=True)

plt.show()

ArtistAnimation

2.2 Demo2: Twinkling stars in three-dimensional space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# Support Chinese
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

# Data
xx = np.array([13, 5, 25, 13, 9, 19, 3, 39, 13, 27])
yy = np.array([4, 38, 16, 26, 7, 19, 28, 10, 17, 18])
zz = np.array([7, 19, 6, 12, 25, 19, 23, 25, 10, 15])
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Draw
star = ax.scatter(xx, yy, zz, c='#C71585', marker='*', s=160,
linewidth=1, edgecolor='black')


# Animate function
def animate(i):
if i % 2:
color = '#C71585'
else:
color = 'white'
next_star = ax.scatter(xx, yy, zz, c=color, marker='*', s=160, linewidth=1, edgecolor='black')
return next_star


def init():
return star


ani = FuncAnimation(fig=fig, func=animate, frames=None, init_func=init, interval=1000, blit=False)

# Set label and title
ax.set_xlabel('x轴')
ax.set_ylabel('y轴')
ax.set_zlabel('z轴')
ax.set_title('3D散点图', fontproperties='simhei', fontsize=14)

plt.tight_layout()
plt.show()

Twinkling stars in three-dimensional space

3. Using basemap to draw statistical map

3.1 Basemap overview

3.2 Demo3: Population distribution of some cities and towns in the United States

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# env var
import os

os.environ['PROJ_LIB'] = r'C:\ProgramData\Anaconda3\Library\share'

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

# support Chinese
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

# 创建 Basemap 对象
map = Basemap(projection='stere', lat_0=90, lon_0=-105, llcrnrlat=23.41,
urcrnrlat=45.44, llcrnrlon=-118.67, urcrnrlon=-64.52,
rsphere=6371200., resolution='l', area_thresh=10000)
map.drawmapboundary() # 绘制地图投影周围边界
map.drawstates() # 绘制州界
map.drawcoastlines() # 绘制海岸线
map.drawcountries() # 绘制国家边界

# 绘制纬线
parallels = np.arange(0., 90, 10.)
map.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=10)

# 绘制经线
meridians = np.arange(-110., -60., 10.)
map.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=10)

posi = pd.read_csv(r"2014_us_cities.csv")

# 从3228组城市数据中选择500 组数据
lat = np.array(posi["lat"][0:500]) # 获取纬度值
lon = np.array(posi["lon"][0:500]) # 获取经度值
pop = np.array(posi["pop"][0:500], dtype=float) # 获取人口数
# 气泡图的气泡大小
size = (pop / np.max(pop)) * 1000
x, y = map(lon, lat)
map.scatter(x, y, s=size)
plt.title('2014年美国部分城镇的人口分布情况')

plt.show()

Population distribution of some cities and towns in the United States

Attachment


Drawing 3D charts and statistical maps
https://www.hardyhu.cn/2022/03/27/Drawing-3D-charts-and-statistical-maps/
Author
John Doe
Posted on
March 27, 2022
Licensed under