Reputation: 83
I visualize my data using Python3 on Windows10 as follows. I try to hide the ticks and tickslabels of colorbar, and plot text inside the colorbar.
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
data = 20 + 100*np.random.rand(30, 30)
#print(data)
plt.imshow(data)
cbar = plt.colorbar(ticks= [], pad=0.015, aspect=12)
x = 10
for index, label in enumerate([str(np.round(np.amin(data),1)), str(np.round(np.amax(data),1))]):
y = np.amin(data) + 0.1*(np.amax(data) - np.amin(data)) + 0.7*index*(np.amax(data) - np.amin(data))
if index == 0:
cbar.ax.text(x, y, label, rotation=90, va='center', color='white', fontsize=16)
else:
cbar.ax.text(x, y, label, rotation=90, va='center', color='black', fontsize=16)
plt.show()
It results in
The text inside the colorbar is misaligned somehow. How to make the text inside the colorbar center-aligned? Is there any suggestion for the value of x
in the script?
Upvotes: 1
Views: 424
Reputation: 80349
You can use 0.5
as x-position and the yaxis transform (y-axis in data, x-axis in axes coordinates).
for index, label in enumerate([str(np.round(np.amin(data), 1)), str(np.round(np.amax(data), 1))]):
y = np.amin(data) + 0.1 * (np.amax(data) - np.amin(data)) + 0.7 * index * (np.amax(data) - np.amin(data))
cbar.ax.text(0.5, y, label, rotation=90, va='center', ha='center',
color='white' if index == 0 else 'black', fontsize=16, transform=cbar.ax.get_yaxis_transform())
Upvotes: 1