I am making a scatter plot in matplotlib and need to change the background of the actual plot to black. I know how to change the face color of the plot using:
fig = plt.figure()
fig.patch.set_facecolor('xkcd:mint green')

My issue is that this changes the color of the space around the plot. How to I change the actual background color of the plot?
Use the set_facecolor(color) method of the axes object, which you've created one of the following ways:
You created a figure and axis/es together
fig, ax = plt.subplots(nrows=1, ncols=1)
You created a figure, then axis/es later
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1) # nrows, ncols, index
You used the stateful API (if you're doing anything more than a few lines, and especially if you have multiple plots, the object-oriented methods above make life easier because you can refer to specific figures, plot on certain axes, and customize either)
plt.plot(...)
ax = plt.gca()
Then you can use set_facecolor:
ax.set_facecolor('xkcd:salmon')
ax.set_facecolor((1.0, 0.47, 0.42))

As a refresher for what colors can be:
matplotlib.colors
Matplotlib recognizes the following formats to specify a color:
- an RGB or RGBA tuple of float values in
[0, 1](e.g.,(0.1, 0.2, 0.5)or(0.1, 0.2, 0.5, 0.3));- a hex RGB or RGBA string (e.g.,
'#0F0F0F'or'#0F0F0F0F');- a string representation of a float value in
[0, 1]inclusive for gray level (e.g.,'0.5');- one of
{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'};- a X11/CSS4 color name;
- a name from the xkcd color survey; prefixed with
'xkcd:'(e.g.,'xkcd:sky blue');- one of
{'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'}which are the Tableau Colors from the ‘T10’ categorical palette (which is the default color cycle);- a “CN” color spec, i.e. 'C' followed by a single digit, which is an index into the default property cycle (
matplotlib.rcParams['axes.prop_cycle']); the indexing occurs at artist creation time and defaults to black if the cycle does not include color.All string specifications of color, other than “CN”, are case-insensitive.
One method is to manually set the default for the axis background color within your script (see Customizing matplotlib):
import matplotlib.pyplot as plt
plt.rcParams['axes.facecolor'] = 'black'
This is in contrast to Nick T's method which changes the background color for a specific axes object. Resetting the defaults is useful if you're making multiple different plots with similar styles and don't want to keep changing different axes objects.
Note: The equivalent for
fig = plt.figure()
fig.patch.set_facecolor('black')
from your question is:
plt.rcParams['figure.facecolor'] = 'black'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With