matplotlib: change title and colorbar text and tick colors

Question:

I wanted to know how to change the color of the ticks in the colorbar and how to change the font color of the title and colorbar in a figure. For example, things obviously are visible in temp.png but not in temp2.png:

import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn

fig = plt.figure()
data = np.clip(randn(250,250),-1,1)
cax = plt.imshow(data, interpolation='nearest')
plt.title('my random fig')
plt.colorbar()

# works fine
plt.savefig('temp.png')
# title and colorbar ticks and text hidden
plt.savefig('temp2.png', facecolor="black", edgecolor="none")

Thanks

Asked By: ahmadh

||

Answers:

(Update: The information in this answer is outdated, please scroll below for other answers which is up to date and better suited to new version)

This can be done by inspecting and setting properties for object handler in matplotlib.

I edited your code and put some explanation in comment:

import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn

fig = plt.figure()
data = np.clip(randn(250,250),-1,1)
cax = plt.imshow(data, interpolation='nearest')

title_obj = plt.title('my random fig') #get the title property handler
plt.getp(title_obj)                    #print out the properties of title
plt.getp(title_obj, 'text')            #print out the 'text' property for title
plt.setp(title_obj, color='r')         #set the color of title to red

axes_obj = plt.getp(cax,'axes')                 #get the axes' property handler
ytl_obj = plt.getp(axes_obj, 'yticklabels')     #get the properties for 
                                                #  yticklabels
plt.getp(ytl_obj)                               #print out a list of properties
                                                #  for yticklabels
plt.setp(ytl_obj, color="r")                    #set the color of yticks to red

plt.setp(plt.getp(axes_obj, 'xticklabels'), color='r') #xticklabels: same

color_bar = plt.colorbar()                            #this one is a little bit
cbytick_obj = plt.getp(color_bar.ax.axes, 'yticklabels')                #tricky
plt.setp(cbytick_obj, color='r')

plt.savefig('temp.png')
plt.savefig('temp2.png', facecolor="black", edgecolor="none")
Answered By: EwyynTomato

Based on previous answer I added two lines to set the colorbar’s box color and colorbar’s ticks color:

import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn

fig = plt.figure()
data = np.clip(randn(250,250),-1,1)
cax = plt.imshow(data, interpolation='nearest')

title_obj = plt.title('my random fig') #get the title property handler
plt.setp(title_obj, color='w')         #set the color of title to white

axes_obj = plt.getp(cax,'axes')                        #get the axes' property handler
plt.setp(plt.getp(axes_obj, 'yticklabels'), color='w') #set yticklabels color
plt.setp(plt.getp(axes_obj, 'xticklabels'), color='w') #set xticklabels color

color_bar = plt.colorbar()                            
plt.setp(plt.getp(color_bar.ax.axes, 'yticklabels'), color='w') # set colorbar  
                                                                # yticklabels color
##### two new lines ####
color_bar.outline.set_color('w')                   #set colorbar box color
color_bar.ax.yaxis.set_tick_params(color='w')      #set colorbar ticks color 
##### two new lines ####

plt.setp(cbytick_obj, color='r')
plt.savefig('temp.png')
plt.savefig('temp3.png', facecolor="black", edgecolor="none")
Answered By: jmb_louis

Previous answer didnt give what I wanted.
This is how I did it:

import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn
data = np.clip(randn(250,250),-1,1)
data = np.ma.masked_where(data > 0.5, data)


fig, ax1 = plt.subplots(1,1)

im = ax1.imshow(data, interpolation='nearest')
cb = plt.colorbar(im)

fg_color = 'white'
bg_color = 'black'

# IMSHOW    
# set title plus title color
ax1.set_title('ax1 title', color=fg_color)

# set figure facecolor
ax1.patch.set_facecolor(bg_color)

# set tick and ticklabel color
im.axes.tick_params(color=fg_color, labelcolor=fg_color)

# set imshow outline
for spine in im.axes.spines.values():
    spine.set_edgecolor(fg_color)    

# COLORBAR
# set colorbar label plus label color
cb.set_label('colorbar label', color=fg_color)

# set colorbar tick color
cb.ax.yaxis.set_tick_params(color=fg_color)

# set colorbar edgecolor 
cb.outline.set_edgecolor(fg_color)

# set colorbar ticklabels
plt.setp(plt.getp(cb.ax.axes, 'yticklabels'), color=fg_color)

fig.patch.set_facecolor(bg_color)    
plt.tight_layout()
plt.show()
#plt.savefig('save/to/pic.png', dpi=200, facecolor=bg_color)

black on white imshow

Answered By: Mattijn

While the other answers are surely correct, it seems this is easier being solved using either styles or specific rcParams, or using the tick_params function

Styles

Matplotlib provides a dark_background style. You may use it e.g. via plt.style.use("dark_background"):

import matplotlib.pyplot as plt
import numpy as np

plt.style.use("dark_background")

fig = plt.figure()
data = np.clip(np.random.randn(150,150),-1,1)
plt.imshow(data)
plt.title('my random fig')
plt.colorbar()  

plt.savefig('temp2.png', facecolor="black", edgecolor="none")
plt.show()

enter image description here

Or, if you need to create the same figure with and without black background styles may be used in a context.

import matplotlib.pyplot as plt
import numpy as np

def create_plot():
    fig = plt.figure()
    data = np.clip(np.random.randn(150,150),-1,1)
    plt.imshow(data)
    plt.title('my random fig')
    plt.colorbar()
    return fig

# create white background plot
create_plot()
plt.savefig('white_bg.png')

with plt.style.context("dark_background"):
    create_plot()
    plt.savefig('dark_bg.png', facecolor="black", edgecolor="none")

Read more about this in the Customizing matplotlib tutorial.

Specific rcParams

You may individually set the required rcParams that compose a style where needed in your script.

E.g. to make any text blue and yticks red:

params = {"text.color" : "blue",
          "xtick.color" : "crimson",
          "ytick.color" : "crimson"}
plt.rcParams.update(params)

This will automatically also colorize the tickmarks.

enter image description here

Customizing ticks and labels

You may also customize the objects in the plot individually. For ticks and ticklabels there is a tick_params method. E.g. to only make the ticks of the colorbar red,

cbar = plt.colorbar()
cbar.ax.tick_params(color="red", width=5, length=10)

enter image description here

Also, you can change the tick labels with:

cax = plt.imshow(data)
cbar = plt.colorbar(orientation='horizontal', alpha=0.8, label ='my label',
                    fraction=0.075, pad=0.07, extend='max')
#get the ticks and transform it to list, if you want to add strings.
cbt = cbar.get_ticks().tolist() 
#edit the new list of ticks, for instance the firs element
cbt[0]='$no$ $data$'
# then, apply the changes on the actual colorbar
cbar.ax.set_xticklabels(cbt)
Answered By: Carlos Ramos
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.