bengen343
bengen343

Reputation: 139

Set background color behind the image in matplotlib

I'm trying to use Matplotlib in Python to display an image and show text at various points over it. I'd like to make the image partially transparent, so to increase the visibility of the text.

However, I want the background color behind the image to be white instead of grey and I can't figure out how to get that change to stick. This is where I'm at.

img = plt.imread("counties.png")
fig, ax = plt.subplots()
plt.axis('off')
plt.text(.6, .68,'matplotlib', ha='center', va='center', 
transform=ax.transAxes, color=(0,.16,.48), fontname='Kanit Light')
plt.text(.5, .5,'test', ha='center', va='center', transform=ax.transAxes, 
color=(0,.16,.48))
ax.imshow(img, alpha=0.05)
plt.show()

Upvotes: 5

Views: 11095

Answers (1)

Serenity
Serenity

Reputation: 36695

To set face color (or background color) of a figure use this function:

fig.patch.set_facecolor('grey')

Or in another way you may call:

plt.rcParams['figure.facecolor'] = 'grey'

Result is like: enter image description here

However without your image result is incomplete. But if you going to save your figure use command like this: plt.savefig('counties2.png', facecolor = fig.get_facecolor(), transparent = True)

Upvotes: 9

Related Questions