Set background color behind image in matplotlib

I am trying to use Matplotlib in Python to display an image and display text at different points. I would like to make the image partially transparent in order to increase the visibility of the text.

However, I want the background color behind the image to be white, not gray, and I can't figure out how to get this change to be pasted. This is where I am.

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()

      

+3


source to share


1 answer


To set the face color (or background color) of a shape, use this function:

fig.patch.set_facecolor('grey')

      

Or else you can call:



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

      

The result looks like this: enter image description here

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

+4


source







All Articles