0

I would like to have different font weights for each of my colorbar labels.

I have tried to let LaTeX format the labels in the following way:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
im = ax.imshow(np.random.rand(50, 50)/20)
cbar = ax.figure.colorbar(im, ticks=np.arange(0, 0.05, 0.01))
cbar.ax.set_yticklabels([r'{\fontsize{50pt}{3em}\selectfont{}{0}}',
                         r'{\fontsize{40pt}{3em}\selectfont{}{0.01}}',
                         r'{\fontsize{30pt}{3em}\selectfont{}{0.03}}',
                         r'{\fontsize{20pt}{3em}\selectfont{}{0.03}}',
                         r'{\fontsize{10pt}{3em}\selectfont{}{0.04}}',
                         r'{\fontsize{1pt}{3em}\selectfont{}{0.05}}', ])

but this only updates the text of the labels to the whole string (e.g., {\fontsize{50pt}{3em}\selectfont{}{0}}). The pyplot TeX demo works for me. Even if this solution would work it would not be ideal as I would probably need to specify everything manually.

Much more convenient would be something like in this question. There, I learned that the font size of single labels of the regular x and y axis can be updated by calling

label = axes.yaxis.get_major_ticks()[2].label
label.set_fontsize(size)

replacing set_fontsize by set_fontweight correctly updates the weight of the selected label. Unfortunately I could not find the equivalent of axes.yaxis.get_major_ticks()[2].label for the colorbar.

Is it possible to change the font weight of individual labels of the colorbar directly? With directly I mean without using a workaround like plotting some new text above existing labels. If this is not possible a solution plotting text above existing labels which automatically uses the position and content the previous labels and only adjusts the font weight would also be appreciated.

Thanks!

Mahelita
  • 1
  • 1
  • `set_fontweight` should work. Can you show a [mcve] of where it doesn't? – ImportanceOfBeingErnest Jun 04 '19 at 11:10
  • Hi @ImportanceOfBeingErnest, thanks for insisting that `set_fontweight` should work! It does when one finds the proper way to extract the text objects defining the labels. I will post an answer to my own question. – Mahelita Jun 04 '19 at 12:36

1 Answers1

0

As pointed out by @ImportanceOfBingErnest , set_fontweight works for setting the weight of single colorbar labels too. I had to try a couple of things to find which call would give me the text objects defining the colorbar labels. They are accessible in cbar.ax.get_yticklabels(). The code snippet below now properly changes the weight of the second colorbar label:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
im = ax.imshow(np.random.rand(50, 50)/20)
cbar = ax.figure.colorbar(im, ticks=np.arange(0, 0.05, 0.01))
cbar.ax.get_yticklabels()[1].set_fontweight(1000)
plt.show()

Output of code (not enough reputation for inline images)

Mahelita
  • 1
  • 1