1. 引言
嘿,亲爱的数据探险家们!你们是否曾梦想过,在二维的屏幕上,让数据跳出束缚,翩翩起舞,展现它那迷人的三维身姿?今天,就让我这位自封的‘数据魔术师’,带你解锁Matplotlib的隐藏技能——3D绘图!想象一下,那些冷冰冰的数字和线条,在Matplotlib的魔法下,瞬间化身为立体城堡、旋转星系或是神秘迷宫。不需要复杂的咒语,只需几行代码,你就能成为这场视觉盛宴的导演。准备好了吗?让我们一起,用Matplotlib绘制3D图,让数据的世界从此不再单调,而是色彩斑斓,妙趣横生!
2. 导包
# 导包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 如果浏览器不显示图片,就需要加上这句话
%matplotlib inline
# 让图片中可以显示中文
plt.rcParams['font.sans-serif'] = "SimHei"
# 让图片中可以显示负号
plt.rcParams["axes.unicode_minus"] = False
# 支持svg矢量图
%config Inlinebackend.figure_format = "svg"
# 3D引擎
from mpl_toolkits.mplot3d.axes3d import Axes3D
3. 三维折线图
fig = plt.figure(figsize=(5, 3))
x = np.linspace(0, 100, 400)
y = np.sin(x)
z = np.cos(x)
# 三维折线图
axes = Axes3D(fig, auto_add_to_figure=False)
fig.add_axes(axes)
axes.plot(x, y, z)
[<mpl_toolkits.mplot3d.art3d.Line3D at 0x1f0ee3b35d0>]
4. 三维散点图
fig = plt.figure(figsize=(5, 3))
axes = Axes3D(fig, auto_add_to_figure=False)
fig.add_axes(axes)
# 画散点图
x = np.random.rand(50)
y = np.random.rand(50)
z = np.random.rand(50)
axes.scatter(x, y, z, color="red", s=100)
<mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x1f0ee1b2e90>
5. 三维柱形图
fig = plt.figure(figsize=(5, 3))
axes = Axes3D(fig, auto_add_to_figure=False)
fig.add_axes(axes)
x = np.arange(1, 5)
for m in x:
axes.bar(
np.arange(4), # y轴
np.random.randint(10, 100, size=4), # z轴
zs=m, # 在x轴的第几个
zdir="x", # 在哪个方向上排列
width=0.6,
alpha=0.7
)
axes.set_xlabel("X轴", fontsize=10, color="r")
axes.set_ylabel("Y轴", fontsize=10, color="g")
axes.set_zlabel("Z轴", fontsize=10, color="b", labelpad=-17)
plt.show()