Home > other >  Format of Matplotlib colorbar
Format of Matplotlib colorbar

Time:04-08

Good day,

I don't seem to be getting the solution to my issue. I have a Matplotlib chart with a colorbar. The range on the colorbar is from 0 to 50,000. I have limited space for the colorbar and would like to format the thousands to e.g. 10k, 20k, 30k, 40k and 50k. How do I do this?

My colorbar's code looks like this:

cb = plt.colorbar(format ='%1.0f')

What do I put in the "format" to change the thousands from 50,000 to 50k?

Thank you!

CodePudding user response:

I'm not really familiar with the format option, so I propose a different solution:

import numpy as np
import matplotlib.pyplot as plt
f = plt.figure()
ax = f.add_subplot(1, 1, 1)
x, y = np.mgrid[-5:5:100j, -5:5:100j]
z = np.cos(np.sqrt(x**2 * y**2)) * 50e03
c = ax.contourf(x, y, z)
cb = plt.colorbar(c)
# get current tick values
tick_values = cb.get_ticks()
# set new tick labels
cb.set_ticklabels([str(int(t / 1000))   "K" for t in tick_values])

CodePudding user response:

This is possible if you use a lambda function as the format option to colorbar. You can then format the ticklabel strings however you wish. To convert to the "50k" format you specify, a simple lambda function can be used where we divide the value by 1000, and add a "k" in the format string, for example:

lambda x, pos: "{:g}k".format(x / 1000)

In a complete, minimal example, this would look something like:

import numpy as np
import matplotlib.pyplot as plt

# some fake data for this example
data = np.arange(0, 50000, 2000).reshape(5, 5)

# create the figure and axes
fig, ax = plt.subplots()

# plot the data
p = ax.pcolormesh(data, vmin=0, vmax=50000)

# define our function to be used to format the tick labels 
kfmt = lambda x, pos: "{:g}k".format(x / 1000)

cb = fig.colorbar(p, ax=ax, format=kfmt)

plt.show()

enter image description here

  • Related