Change facecolor in text matplotlib

Question:

I want to change the text and the facecolor in a textbox that I have on a graph.

I create my text box like this :

props = dict(boxstyle='round', facecolor='red', alpha=0.3)

ax.text(0.03, 0.97, 'test', transform=ax.transAxes, fontsize=10, verticalalignment='top', bbox=props)

Changing the text is fine, I do :

ax.texts[-1].set_text('new text')

However I cannot find the command to change the color.

Basically I would like something like

ax.texts[-1].set_color('blue').
Asked By: Maxi

||

Answers:

You can do this by accessing the patch object associated with the text box. I have found this example helpful.

from pylab import subplot, show, draw
ax = subplot(111)
props = dict(boxstyle='round', facecolor='red', alpha=0.3) 
t = ax.text(0.03, 0.97, 'test', transform=ax.transAxes, fontsize=10, verticalalignment='top', bbox=props)
show()
bb = t.get_bbox_patch()
bb.set_facecolor('blue')
draw()
Answered By: Molly

I think the following is simplier:

t = ax.text(0.03, 0.97, 'test', transform=ax.transAxes, fontsize=10, verticalalignment='top', `bbox=dict(facecolor='blue', alpha=0.5)`)

Simply putting in: bbox=dict(facecolor='blue', alpha=0.5) in the ax.text statement changes the color. I added the alpha to indicate that other attributes can also be changed.

Answered By: user3644627
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.