Home > Blockchain >  How to set the ticks in matplotlib colorbar to be at the minimum and maximum value
How to set the ticks in matplotlib colorbar to be at the minimum and maximum value

Time:06-27

I have a very simple plot of matplotlib.contourf like the following:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 10)
y = np.linspace(0, 10, 10)
xx,yy = np.meshgrid(x,y)
X = np.array([xx,yy]).reshape(2,-1)

func_plot = X[0]   X[1]
func_plot = np.atleast_2d(func_plot).reshape(10, 10)

fig, ax = plt.subplots(figsize=(13,7))
ax = plt.subplot(121)
cntr = plt.contourf(x,y,func_plot,100,vmin = 0, vmax = 20, alpha = 1)
cbar = fig.colorbar(cntr,orientation="vertical")

Basically I expect to plot a contour image with minimum value = 0 and maximum value = 20. Which gives us the following image: The result of the contour plot with min. val. = 0, and max. val. = 20.

As you can see from the graph, the ticks at the colorbar starts at 0.00 and ends at 19.8 (the highest tick). However, I want the ticks to end at the top of the bar at the exact maximum value spot of 20 (instead of showing 19.8 as the highest tick value). How can I do that?

I'm sure there's a really simple way to tackle the problem. Thank you for your time.

CodePudding user response:

Colorbars are my bane. This problem is relatively simple yet it took me a few minutes.

Add this line to the end of your code:

cbar.set_ticks(np.arange(0, 21, 5)) # 21 to guarantee 20 is included.

To get this:

enter image description here

  • Related