现在我有一个稀疏矩阵,里面的值是药物相互作用的分数,怎么画出它的分布图
时间: 2024-02-24 16:59:07 浏览: 25
您可以使用 `matplotlib` 库中的 `imshow()` 方法来画出稀疏矩阵的分布图。不过,由于稀疏矩阵中大部分元素都是 0,因此需要对数据进行预处理。以下是一个简单的代码示例:
```python
import numpy as np
from scipy.sparse import csr_matrix
import matplotlib.pyplot as plt
# 创建一个稀疏矩阵
data = np.array([1, 2, 3, 4, 5, 6])
row_indices = np.array([0, 0, 1, 1, 2, 2])
col_indices = np.array([0, 1, 0, 1, 0, 1])
sparse_matrix = csr_matrix((data, (row_indices, col_indices)), shape=(3, 2))
# 将稀疏矩阵转换为密集矩阵,并将0值替换为NaN
dense_matrix = sparse_matrix.toarray()
dense_matrix[dense_matrix == 0] = np.nan
# 画出分布图
plt.imshow(dense_matrix, cmap='viridis')
plt.colorbar()
plt.show()
```
在这个示例中,我们首先将稀疏矩阵转换为密集矩阵,并将其中的 0 值替换为 NaN。然后,我们使用 `imshow()` 方法将密集矩阵画出来,使用 `cmap` 参数设置颜色映射,使用 `colorbar()` 方法添加颜色条。最后,使用 `show()` 方法显示图像。