mcqconor
mcqconor

Reputation: 25

How to put color behind axes in python?

I'm trying to make some plots in python 3 for a data science project, and I'm having an issue where there is no color behind the text on my axes when I save it. Here's my code with an example plot:

plt.plot(play_num_2019[g], home_prob_2019[g], color = getColor(home_teams_2019[g]))
plt.plot(play_num_2019[g], away_prob_2019[g], color = getColor(away_teams_2019[g]))
plt.xlabel("Play Number")
plt.ylabel("Win Probability")
plt.legend([home_teams_2019[g], away_teams_2019[g]])
fig = plt.figure()
fig.patch.set_facecolor('xkcd:white')

Plot

Upvotes: 1

Views: 395

Answers (2)

William Miller
William Miller

Reputation: 10320

If you want to set the facecolor for a figure you can either use matplotlib.rcParams to set the a facecolcolor globally - for all figures - or for a single figure you can specify the facecolor in calling plt.savefig(). If you want to set the facecolor using fig.patch.set_facecolor() you can then simply use fig.get_facecolor() in savefig(). For example:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, np.pi*4, 100)

fig = plt.figure()
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(np.sin(x)))
fig.patch.set_facecolor((0.68, 0.78, 0.91))

plt.savefig('/path/to/output.png', facecolor = fig.get_facecolor())

Output

enter image description here

If you want this color applied behind the plot area as well then you must pass transparent=True in plt.savefig() which will give you

enter image description here

Or - as I prefer - you can set the alpha of the axes patch like so

plt.gca().patch.set_alpha(0.7)

or the like. This will produce

enter image description here


Note   -   Setting the facecolor to 'xkcd:white' won't have any effect because the corresponding RGB values are (1.0, 1.0, 1.0) - identical to the default facecolor.

Upvotes: 0

ilke444
ilke444

Reputation: 2741

matplotlib.rcParams contains the plot parameters for matplotlib, stored in matplotlibrc file. You can change the parameters either directly in the matplotlibrc file (as explained here), or in your code, just before plotting. Here is an example to change the figure background color as you requested:

import matplotlib as mpl
import matplotlib.plot as plt

plt.plot(play_num_2019[g], home_prob_2019[g], color = getColor(home_teams_2019[g]))
plt.plot(play_num_2019[g], away_prob_2019[g], color = getColor(away_teams_2019[g]))
plt.xlabel("Play Number")
plt.ylabel("Win Probability")
mpl.rcParams['figure.facecolor'] = 'r' # <--- here is the line for changing the background to red
plt.legend([home_teams_2019[g], away_teams_2019[g]])
fig = plt.figure()
fig.patch.set_facecolor('xkcd:white')

If you want to change it only when the figure is saved, change the following parameter instead.

mpl.rcParams['savefig.facecolor'] = 'r'

Upvotes: 1

Related Questions