如何在matplotlib中绘制矩阵的特定部分?

时间:2015-12-04 06:03:58

标签: python matplotlib

我有一个表示空心方块中温度分布的矩阵(希望附图有帮助)。问题在于板中的空心部分不代表任何固体材料,因此我需要从图中排除这部分。

enter image description here

模拟返回np.array()温度结果(当然除了空心部分)。这是我定义网格尺寸的部分:

import numpy as np

plate_height = 0.4 #meters
hollow_square_height = 0.2 #meters

#discretization data
delta_x = delta_y = 0.05 #meters
grid_points_n = (plate_height/delta_x) + 1

grid = np.zeros(shape=(grid_points_n, grid_points_n))
# the simulation assures that the hollow part will remain zero valued.

那么,我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

您可以掩盖您不希望在计算,绘图等中使用的值,而不是更改原始数据:

import matplotlib.pyplot as plt
import numpy as np

data = [
    [11, 11, 12, 13],
    [9, 0, 0, 12],
    [8, 0, 0, 11],
    [8, 9, 10, 11]
]

#Here's what you have:
data_array = np.array(data)

#Mask every position where there is a 0:
masked_data = np.ma.masked_equal(data_array, 0)

#Plot the matrix:
fig = plt.figure()
ax = fig.gca()
ax.matshow(masked_data, cmap=plt.cm.autumn_r) #_r => reverse the standard color map
plt.show()
#plt.savefig('heatmap.png')

enter image description here

答案 1 :(得分:1)

用nan替换零,在任何绘图中都忽略nan值。例如:

import matplotlib.pyplot as plt
from numpy import nan,matrix

M = matrix([
    [20,30,25,20,50],
    [22,nan,nan,nan,27],
    [30,nan,nan,nan,20],
    [33,nan,nan,nan,31],
    [21,28,29,23,36]])

fig = plt.figure()
ax = fig.add_subplot(111)
ax.matshow(M, cmap=plt.cm.jet) # Show matrix color
plt.show()

您可以在矩阵中用nan替换零,如下所示:

from numpy import nan

A[A==0.0]=nan  # A is your matrix