简体   繁体   中英

matplotlib remove the ticks (axis) from the colorbar

I want to remove the (ticks) axis with numbers to the right of the colorbar. I am using matplotlib with python as follows:

f = plt.figure()
ax = f.add_subplot(1,1,1)
i = ax.imshow(mat, cmap= 'gray')
cbar = f.colorbar(i)

在此处输入图像描述

If you just want to remove the ticks but keep the ticklabels, you can set the size of the ticks to be 0 as following

f = plt.figure()
ax = f.add_subplot(1,1,1)
mat = np.arange(100).reshape((10, 10))
i = ax.imshow(mat, cmap= 'viridis')
cbar = f.colorbar(i)
cbar.ax.tick_params(size=0)

在此处输入图像描述

If you want to remove both, the ticks and the labels, you can use set_ticks([]) by passing an empty list.

cbar.set_ticks([])

在此处输入图像描述

Another option is to provided a formatter or locator. Here two combinations of:

  • a formatter which sets any value to an empty sting ('')
  • a locator that doesn't place a tick.

See the official matplotlib docs for more formatters or locators.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots(ncols=1)

mat = np.arange(100).reshape((10, 10))
cs = ax.imshow(mat, cmap= 'viridis')

divider = make_axes_locatable(ax)
dvider_kwargs = dict(position="right", size="15%", pad=0.5)
fig.colorbar(cs,
             cax=divider.append_axes(**dvider_kwargs),
             format = matplotlib.ticker.FuncFormatter(lambda x, pos: ''),
             ticks = matplotlib.ticker.FixedLocator([]))

fig.colorbar(cs, 
             cax=divider.append_axes(**dvider_kwargs),
             format = matplotlib.ticker.FuncFormatter(lambda x, pos: ''))

fig.colorbar(cs, 
             cax=divider.append_axes(**dvider_kwargs))
             
plt.tight_layout()

With make_axes_locatable and cax=divider.append_axes the colorbars have all the same size.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM