Skip to main content
 首页 » 编程设计

python之matplotlib,pyplot : custom color for a specific data value

2024年10月25日9kevingrace

我正在为我的数据生成热图。

一切正常,但我有一个小问题。我的数据(数字)是从 0 到 10.000。

0 没有任何意义(没有数据),目前 0 的字段只采用我的颜色标度中的最低颜色。我的问题是如何使 0 的数据具有完全不同的颜色(例如黑色或白色)

只要看图片就可以更好地理解我的意思:

我的代码(片段)如下所示:

     matplotlib.pyplot.imshow(results, interpolation='none') 
     matplotlib.pyplot.colorbar(); 
     matplotlib.pyplot.xticks([0, 1, 2, 3, 4, 5, 6, 7, 8], [10, 15, 20, 25, 30, 35, 40, 45, 50]); 
     matplotlib.pyplot.xlabel('Population') 
     matplotlib.pyplot.yticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 10, 15, 20, 25, 30, 'serial']); 
     matplotlib.pyplot.ylabel('Communication Step'); 
     axis.xaxis.tick_top(); 
     matplotlib.pyplot.savefig('./results_' + optimisationProblem + '_dim' + str(numberOfDimensions) + '_' + statisticType + '.png'); 
     matplotlib.pyplot.close(); 

请您参考如下方法:

如果您对值 0 和 0.0001 之间的平滑过渡不感兴趣,您可以将每个等于 0 的值设置为南。这将导致白色,而 0.0001 仍将是 deep blue-ish。

在下面的代码中,我包含了一个示例。我随机生成数据。因此,我从数组中选择一个元素并将其设置为 NaN。这导致颜色为白色。我还包括一行,您可以在其中将等于 0 的每个数据点设置为 NaN。

import numpy 
import matplotlib.pyplot as plt 
 
#Random data 
data = numpy.random.random((10, 10)) 
 
#Set all data points equal to zero to NaN 
#data[data == 0.] = float("NaN") 
 
#Set single data value to nan 
data[2][2] = float("NaN") 
 
fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1) 
 
ax.imshow(data, interpolation = "nearest") 
 
plt.show()