rshuka
rshuka

Reputation: 23

matplotlib, pyplot : custom color for a specific data value

I am generating a heat map for my data.

everything works fine, but I have a little problem. My data (numbers) are from 0 to 10.000.

0 means nothing (no data) and at the moment the field with 0 just take the lowest color of my color scala. My problem is how to make the data with 0 to have a total different color (e.g. black or white)

Just see the Picture to better understand what i mean:

enter image description here

My code (snippet) looks like this:

     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();

Upvotes: 2

Views: 1496

Answers (1)

The Dude
The Dude

Reputation: 4005

If you are not interested in a smooth transition between the values 0 and 0.0001, you can just set every value that equals 0 to NaN. This will result in a white color whereas 0.0001 will still be deep blue-ish.

In the following code I include an example. I generate the data randomly. I therefore select a single element from my array and set it to NaN. This results in the color white. I also included a line in which you can set every data point that equals 0 to 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()

enter image description here

Upvotes: 2

Related Questions