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')
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')
mpl.rcParams['savefig.facecolor'] = 'r'
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
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
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
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.