1

I want to change the background color of a plot created with imshow. However, the way to change the background only works based on the figure object

(Matplotlib figure facecolor (background color))

...i.e., you need to use the figure object name: e.g.,

rect.set_facecolor('red')

I have read that imshow creates a figure automatically.

(matplotlib plot and imshow)

Therefore, how can I tell what the automatically-created figure's name is, so that I can use set_facecolor( )

CodeGuyJr
  • 79
  • 1
  • 2
  • 9

1 Answers1

6

Using pyplot you can create the figure by calling any plotting function. I.e.

import matplotlib.pyplot as plt
plt.imshow(data)
plt.show()

creates a figure and shows it.

In this case you may change the figure background color via

plt.gcf().set_facecolor("red")

However it is often useful to create the figure explicitely:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.imshow(data)
fig.set_facecolor("red")
plt.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Thanks a lot @ImportanceOfBeingErnest – CodeGuyJr Aug 08 '18 at 16:56
  • @CodeGuyJr Can you mark his answer as the correct answer? Because then other people can mark similar questions as duplicates of this one – zwep Dec 10 '18 at 10:06
  • 1
    @zwep Note that all that's needed for close-voting a question as duplicate is that the dupe-target has an answer and that answer is either upvoted **or** accepted. Hence if you want to close-vote a question, you may just upvote one of the target's answers to be able to do so. – ImportanceOfBeingErnest Dec 10 '18 at 10:11
  • @ImportanceOfBeingErnest Upvoted it. Thanks for the instruction; I am a noob here. – CodeGuyJr Jan 20 '19 at 17:58
  • @Bazingaa Well, not out of disregard, but simply because it wasn't apparent to me that "mark correct" = click that little check mark. I just "upvoted" something and Stackoverflow prompted me to click the green arrow. Now I know. – CodeGuyJr Jan 20 '19 at 20:04
  • @CodeGuyJr: No issues. I thought you already knew. But now you know :) Happy Stack Overflowing ;) – Sheldore Jan 20 '19 at 20:06
  • @Bazingaa Thanks :) – CodeGuyJr Jan 20 '19 at 20:08
  • @Bazingaa Will do. – CodeGuyJr Jan 20 '19 at 20:10