plt绘画3d散点图举例,并根据类别数组绘制颜色和形状
时间: 2024-01-17 14:05:24 浏览: 57
Python+matplotlib绘制不同大小和颜色散点图实例
5星 · 资源好评率100%
好的,可以使用 matplotlib 库来绘制 3D 散点图,并根据类别数组绘制颜色和形状,具体步骤如下:
首先,导入相关的库和模块:
```python
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
```
接着,生成三组随机数据,并为每一组数据设置一个类别数组:
```python
n = 100
x1 = np.random.rand(n)
y1 = np.random.rand(n)
z1 = np.random.rand(n)
category1 = np.zeros(n)
x2 = np.random.rand(n)
y2 = np.random.rand(n)
z2 = np.random.rand(n)
category2 = np.ones(n)
x3 = np.random.rand(n)
y3 = np.random.rand(n)
z3 = np.random.rand(n)
category3 = np.full(n, 2)
```
然后,创建一个 3D 图形对象:
```python
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
```
接着,使用 scatter() 方法分别绘制三组散点图,并为每一组散点图设置颜色和形状:
```python
ax.scatter(x1, y1, z1, c=category1, marker='o', cmap='Reds')
ax.scatter(x2, y2, z2, c=category2, marker='s', cmap='Greens')
ax.scatter(x3, y3, z3, c=category3, marker='^', cmap='Blues')
```
最后,设置坐标轴标签和标题,并显示图形:
```python
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.title('3D Scatter Plot with Different Colors and Markers Based on Category')
plt.show()
```
完整代码如下:
```python
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
n = 100
x1 = np.random.rand(n)
y1 = np.random.rand(n)
z1 = np.random.rand(n)
category1 = np.zeros(n)
x2 = np.random.rand(n)
y2 = np.random.rand(n)
z2 = np.random.rand(n)
category2 = np.ones(n)
x3 = np.random.rand(n)
y3 = np.random.rand(n)
z3 = np.random.rand(n)
category3 = np.full(n, 2)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x1, y1, z1, c=category1, marker='o', cmap='Reds')
ax.scatter(x2, y2, z2, c=category2, marker='s', cmap='Greens')
ax.scatter(x3, y3, z3, c=category3, marker='^', cmap='Blues')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.title('3D Scatter Plot with Different Colors and Markers Based on Category')
plt.show()
```
运行后,会得到一个 3D 散点图,每一组散点图的点具有不同的颜色和形状,颜色和形状根据类别数组设置。
阅读全文