用Matplotlib绘制二维热图

2024-04-25 00:41:05 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

Seaborn处理大量的手工工作,并在图表的侧面自动绘制渐变等

import numpy as np
import seaborn as sns
import matplotlib.pylab as plt

uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, linewidth=0.5)
plt.show()

enter image description here

或者,您甚至可以绘制正方形矩阵的上/下左/右三角形,例如一个正方形且对称的相关矩阵,因此无论如何,绘制所有值都是多余的。

corr = np.corrcoef(np.random.randn(10, 200))
mask = np.zeros_like(corr)
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
    ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True,  cmap="YlGnBu")
    plt.show()

enter image description here

带参数interpolation='nearest'cmap='hot'^{}函数应该做您想要的事情。

import matplotlib.pyplot as plt
import numpy as np

a = np.random.random((16, 16))
plt.imshow(a, cmap='hot', interpolation='nearest')
plt.show()

enter image description here

对于二维numpy数组,只需使用imshow()就可以帮助您:

import matplotlib.pyplot as plt
import numpy as np


def heatmap2d(arr: np.ndarray):
    plt.imshow(arr, cmap='viridis')
    plt.colorbar()
    plt.show()


test_array = np.arange(100 * 100).reshape(100, 100)
heatmap2d(test_array)

The heatmap of the example code

此代码生成连续热图。

您可以从here中选择另一个内置的colormap

相关问题 更多 >