Reputation: 2016
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
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
Reputation: 39062
Here is one solution using some random data for demonstration purposes. The idea is as follows:
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)
Upvotes: 5