Benny Ae
Benny Ae

Reputation: 2016

Add top and bottom value label to color bar

I would like to add top and bottom values to my color bar. So the range the top value is the max number of the values in my data, and bottom is the min number of my data

enter image description here

import numpy as np
import matplotlib.pyplot as plt
import matplotlib

data = np.genfromtxt("E:\\data\\data1.txt", delimiter="\t")
minVal =  np.min(data[np.nonzero(data)])
maxVal =  np.max(data[np.nonzero(data)])

fig, ax = plt.subplots()
im = ax.imshow(data, cmap='Purples',
           interpolation='nearest',
           norm=matplotlib.colors.LogNorm(),
           vmin=minVal,vmax = maxVal,    
               )

cbar = fig.colorbar(im)

print("min ",minVal)
print("max", maxVal)

plt.show()

Upvotes: 8

Views: 3954

Answers (1)

Sheldore
Sheldore

Reputation: 39062

Here is one solution using some random data for demonstration purposes. The idea is as follows:

  • Get the existing ticks and their labels from the colorbar
  • Add two ticks and the labels at the minimum and the maximum values
  • Set the new ticks and the new labels

import numpy as np
import matplotlib.pyplot as plt
import matplotlib

data = np.random.randint(0, 50000, (50,50))
minVal =  np.min(data[np.nonzero(data)])
maxVal =  np.max(data[np.nonzero(data)])

print (minVal, maxVal)
# 4, 49983    

fig, ax = plt.subplots()
im = ax.imshow(data, cmap='Purples', interpolation='nearest',
           norm=matplotlib.colors.LogNorm(), vmin=minVal,vmax = maxVal,)

cbar = fig.colorbar(im)

# Get the default ticks and tick labels
ticklabels = cbar.ax.get_ymajorticklabels()
ticks = list(cbar.get_ticks())

# Append the ticks (and their labels) for minimum and the maximum value
cbar.set_ticks([minVal, maxVal] + ticks)
cbar.set_ticklabels([minVal, maxVal] + ticklabels)

enter image description here

Upvotes: 5

Related Questions