Python 使用 Matplotlib 绘制二维热图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33282368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:08:18  来源:igfitidea点击:

Plotting a 2D heatmap with Matplotlib

pythonnumpymatplotlib

提问by Karnivaurus

Using Matplotlib, I want to plot a 2D heat map. My data is an n-by-n Numpy array, each with a value between 0 and 1. So for the (i, j) element of this array, I want to plot a square at the (i, j) coordinate in my heat map, whose color is proportional to the element's value in the array.

使用 Matplotlib,我想绘制 2D 热图。我的数据是一个 n×n Numpy 数组,每个数组的值都在 0 到 1 之间。所以对于这个数组的 (i, j) 元素,我想在我的 (i, j) 坐标处绘制一个正方形热图,其颜色与数组中元素的值成正比。

How can I do this?

我怎样才能做到这一点?

回答by P. Camilleri

The imshow()function with parameters interpolation='nearest'and cmap='hot'should do what you want.

imshow()带参数的功能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

在此处输入图片说明

回答by kilojoules

Here's how to do it from a csv:

以下是从 csv 执行此操作的方法:

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata

# Load data from CSV
dat = np.genfromtxt('dat.xyz', delimiter=' ',skip_header=0)
X_dat = dat[:,0]
Y_dat = dat[:,1]
Z_dat = dat[:,2]

# Convert from pandas dataframes to numpy arrays
X, Y, Z, = np.array([]), np.array([]), np.array([])
for i in range(len(X_dat)):
        X = np.append(X, X_dat[i])
        Y = np.append(Y, Y_dat[i])
        Z = np.append(Z, Z_dat[i])

# create x-y points to be used in heatmap
xi = np.linspace(X.min(), X.max(), 1000)
yi = np.linspace(Y.min(), Y.max(), 1000)

# Z is a matrix of x-y values
zi = griddata((X, Y), Z, (xi[None,:], yi[:,None]), method='cubic')

# I control the range of my colorbar by removing data 
# outside of my range of interest
zmin = 3
zmax = 12
zi[(zi<zmin) | (zi>zmax)] = None

# Create the contour plot
CS = plt.contourf(xi, yi, zi, 15, cmap=plt.cm.rainbow,
                  vmax=zmax, vmin=zmin)
plt.colorbar()  
plt.show()

where dat.xyzis in the form

dat.xyz表格中的哪里

x1 y1 z1
x2 y2 z2
...

回答by PyRsquared

Seaborntakes care of a lot of the manual work and automatically plots a gradient at the side of the chart etc.

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

在此处输入图片说明

Or, you can even plot upper / lower left / right triangles of square matrices, for example a correlation matrix which is square and is symmetric, so plotting all values would be redundant anyway.

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

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

在此处输入图片说明

回答by Erasmus Cedernaes

I would use matplotlib's pcolor/pcolormeshfunction since it allows nonuniform spacing of the data.

我会使用 matplotlib 的pcolor/ pcolormesh函数,因为它允许数据的非均匀间距。

Example taken from matplotlib:

取自matplotlib 的示例:

import matplotlib.pyplot as plt
import numpy as np

# generate 2 2d grids for the x & y bounds
y, x = np.meshgrid(np.linspace(-3, 3, 100), np.linspace(-3, 3, 100))

z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
# x and y are bounds, so z should be the value *inside* those bounds.
# Therefore, remove the last value from the z array.
z = z[:-1, :-1]
z_min, z_max = -np.abs(z).max(), np.abs(z).max()

fig, ax = plt.subplots()

c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
ax.set_title('pcolormesh')
# set the limits of the plot to the limits of the data
ax.axis([x.min(), x.max(), y.min(), y.max()])
fig.colorbar(c, ax=ax)

plt.show()

pcolormesh plot output

pcolormesh 绘图输出

回答by huangbiubiu

For a 2d numpyarray, simply use imshow()may help you:

对于二维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

示例代码的热图

This code produces a continuous heatmap.

此代码生成一个连续的热图。

You can choose another built-in colormapfrom here.

您可以colormap这里选择另一个内置。