plt绘画3d散点图举例,不同类型的点具有不同的形状和颜色
时间: 2023-10-10 08:08:40 浏览: 79
好的,可以使用 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)
color1 = 'r'
marker1 = 'o'
x2 = np.random.rand(n)
y2 = np.random.rand(n)
z2 = np.random.rand(n)
color2 = 'g'
marker2 = 's'
x3 = np.random.rand(n)
y3 = np.random.rand(n)
z3 = np.random.rand(n)
color3 = 'b'
marker3 = '^'
```
然后,创建一个 3D 图形对象:
```python
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
```
接着,使用 scatter() 方法分别绘制三组散点图,并为每一组散点图设置颜色和形状:
```python
ax.scatter(x1, y1, z1, c=color1, marker=marker1)
ax.scatter(x2, y2, z2, c=color2, marker=marker2)
ax.scatter(x3, y3, z3, c=color3, marker=marker3)
```
最后,设置坐标轴标签和标题,并显示图形:
```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')
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)
color1 = 'r'
marker1 = 'o'
x2 = np.random.rand(n)
y2 = np.random.rand(n)
z2 = np.random.rand(n)
color2 = 'g'
marker2 = 's'
x3 = np.random.rand(n)
y3 = np.random.rand(n)
z3 = np.random.rand(n)
color3 = 'b'
marker3 = '^'
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x1, y1, z1, c=color1, marker=marker1)
ax.scatter(x2, y2, z2, c=color2, marker=marker2)
ax.scatter(x3, y3, z3, c=color3, marker=marker3)
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')
plt.show()
```
运行后,会得到一个 3D 散点图,每一组散点图的点具有不同的颜色和形状。
阅读全文