Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting tick values on top and bottom of matplotlib colorbar

My current code looks like this:

import matplotlib.pyplot as plt
import numpy as np

s = 5
x = np.linspace(-10,10,100)
y = np.linspace(-10,10,100)
xg = np.exp(-(x**2)/(s**2))
yg = np.exp(-(y**2)/(s**2))

vals = np.meshgrid(xg,yg)

fig, ax = plt.subplots()

cax = ax.imshow(vals[0]*vals[1])
ax.axis("off")
fig.colorbar(cax,ticks=[0.0,1.0],label="Values (0-1)")

Which produces the following output:

enter image description here

I would like the tick values to be on top and bottom of the colorbar (and not on the sides) as in here:

enter image description here

At the moment, I have done this using Illustrator but I am planning to generate a lot of images like this (for a video) and would like to make these plots automatic.

like image 252
Matt Avatar asked Oct 15 '25 08:10

Matt


1 Answers

If you want them nicely centered on the colorbar, then you can't use the yticklabels to achieve this. But you can add the two text fields manually like this:

cb = plt.colorbar(im, ticks=[], label="Values (0-1)")
cb.ax.text(0.5, -0.01, '0', transform=cb.ax.transAxes, 
    va='top', ha='center')
cb.ax.text(0.5, 1.0, '1', transform=cb.ax.transAxes, 
    va='bottom', ha='center')

Result: enter image description here

like image 77
hitzg Avatar answered Oct 16 '25 21:10

hitzg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!