Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 512
bengen343 Avatar asked Apr 23 '17 23:04

bengen343


People also ask

How do I change the background color in matplotlib?

Matplotlib change background color inner and outer color We can set the Inner and Outer colors of the plot. set_facecolor() method is used to change the inner background color of the plot. figure(facecolor='color') method is used to change the outer background color of the plot.

How do I make the background transparent in matplotlib?

If you just want the entire background for both the figure and the axes to be transparent, you can simply specify transparent=True when saving the figure with fig. savefig . If you want more fine-grained control, you can simply set the facecolor and/or alpha values for the figure and axes background patch.


1 Answers

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)

like image 62
Serenity Avatar answered Sep 27 '22 21:09

Serenity