编写函数画P维变量的两两散点图,Python代码。
时间: 2024-10-11 17:07:27 浏览: 24
Python Matplotlib实现三维数据的散点图绘制
5星 · 资源好评率100%
在Python中,我们可以使用matplotlib库以及numpy库来绘制高维空间中的散点图。以下是一个简单的例子,展示如何编写一个函数,用于生成P维空间中每对变量之间的二维散点图:
```python
import matplotlib.pyplot as plt
import numpy as np
def plot.pairplot_high_dim(data, dimensions, labels=None):
# 创建一个P x P的子图网格
fig, axs = plt.subplots(nrows=len(dimensions), ncols=len(dimensions), figsize=(8 * len(dimensions), 6 * len(dimensions)))
if labels is not None:
assert len(labels) == len(dimensions), "Number of labels must match the number of dimensions"
for i in range(len(dimensions)):
for j in range(i, len(dimensions)):
ax = axs[i, j] if i < j else axs[j, i]
# 如果是主对角线,只显示数据范围
if i == j:
ax.set_title(f'Dimension {i+1}')
ax.scatter(*data[:, dimensions[i]].T)
ax.axis('equal')
ax.set_yticklabels([])
ax.set_xticklabels([])
else:
# 绘制一对变量的散点图
ax.scatter(data[:, dimensions[i]], data[:, dimensions[j]])
ax.set_xlabel(labels[dimensions[i]] if labels else f'Dimension {i+1}')
ax.set_ylabel(labels[dimensions[j]] if labels else f'Dimension {j+1}')
# 调整子图间的间距
plt.tight_layout()
# 使用示例
data = np.random.rand(100, 5) # 假设我们有5维数据
dimensions = [0, 1, 2, 3, 4] # 我们要画出所有维度对
labels = ['Dimension ' + str(i) for i in range(1, len(dimensions)+1)] if labels is None else labels
plot.pairplot_high_dim(data, dimensions, labels)
# 显示图形
plt.show()
阅读全文