formatting colorbar in topomap

Hello,

I am using mne.viz.plot_evoked_topomap and would like the colorbar to show only 3 ticks (the min, the middle and the max)

It seems like the argument cbar_fmt in the plot_evoked_topomap could permit this.
Does anyone has an example using the cbar_fmt ?

cbar_fmt str

Formatting string for colorbar tick labels. See Format Specification Mini-Language for details

Many thanks!

Ana

Hi,

This may not be MNE-related, really… I don’t think the functions of MNE expose this colorbar property.

The cbar_fmt you mentioned is to format the number shown at each tick into a specific string (how many digits after the point, or leading zeros, or scientific number with exponents, etc…).

To alter the tick locations, you can pass the ticks you want to the colorbar call when you create it, e.g. plt.colorbar(im, cax=cax, ticks=[np.min(data), np.median(data), np.max(data)]). And more generally, you can use Locators (see Matplotlib’s documentation) to alter the position of ticks.

In my opinion, it is much easier to create your own colorbar rather than altering the one that MNE outputs with plot_evoked_topomap.

Here is an example with either a colorbar added by “hand” to the final figure or by modifying properties of the existing colorbar:

import mne
import numpy as np
import matplotlib.pyplot as plt

own_cbar = True # switch between creating a colorbar or using the one from the plot_topomap call

# Random data
montage = mne.channels.montage.make_standard_montage('biosemi64')
info = mne.create_info(montage.ch_names, 100, 'eeg')
info.set_montage(montage)
evoked = mne.EvokedArray(np.random.randn(100, 64).T * 1e-6, info)

# Create figures with 3 topographies
fig = mne.viz.plot_evoked_topomap(evoked, times=[0.1, 0.25, 0.5], colorbar=not own_cbar, show=False);
im = fig.axes[-1 if own_cbar else -2].images[-1] # select the last image to grab/create colorbar
if own_cbar:
    cax = fig.axes[-1].inset_axes([1.15, 0.05, 0.075, 0.9])
    cb = fig.colorbar(im, cax=cax)
    cax.set_title(r'$\mu$V')
else:
    cb = im.colorbar
# The locator is what defines the tick on the colorbar object in matplotlib    
cb.locator = plt.LinearLocator(numticks=3)
cb.update_ticks()
plt.show()

example_cbar

1 Like

@Hugo-W Thank you for this. Most useful.