Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background color of the title of legend

In the example below, how can I change the background color of "Title" to be red (with alpha=.5), not the font color of "Title"?

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3,], [1,2,3], label='Series')
legend = ax.legend(title='Title')

# Access to the legend title box adapted from
# https://stackoverflow.com/a/63570572
legend._legend_title_box._text.set_color('red')

enter image description here

like image 893
jII Avatar asked Feb 02 '26 21:02

jII


1 Answers

You can change the color of the bounding box of the title text:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3, ], [1, 2, 3], label='Series')
legend = ax.legend(title='Title')

legend._legend_title_box._text.set_bbox(dict(facecolor='red', alpha=0.3, lw=0))

plt.show()

change background of title box of legend

PS: For the red background to span the entire width of the legend frame, you could pad the title with whitespace, as proposed by Trenton Mckinney. E.g.

legend = ax.legend(title=f'{"Title": ^15}', frameon=False)

fill the background to width

like image 112
JohanC Avatar answered Feb 05 '26 09:02

JohanC