- How to Change Plot Background in Matplotlib
- Importing Data and Libraries
- Creating a Plot
- Change Plot Background in Matplotlib
- Change Axes Background in Matplotlib
- Change Figure Background in Matplotlib
- Free eBook: Git Essentials
- Add Image to Plot Background in Matplotlib
- Conclusion
- Data Visualization in Python
- Change Background Color of Plot in Matplotlib
- How to change background color in matplotlib?
- Examples
- 1. Custom face color for axes object
- 2. Set a default axes face color for all plots
- How to change background color in Matplotlib with Python
- Changing the background color of the graph in Matplotlib with Python
How to Change Plot Background in Matplotlib
Matplotlib is one of the most widely used data visualization libraries in Python. From simple to complex visualizations, it’s the go-to library for most.
In this tutorial, we’ll take a look at how to change the background of a plot in Matplotlib.
Importing Data and Libraries
Let’s import the required libraries first. We’ll obviously need Matplotlib, and we’ll use Pandas to read the data:
import matplotlib.pyplot as plt import pandas as pd
Specifically, we’ll be using the Seattle Weather Dataset:
weather_data = pd.read_csv("seattleWeather.csv") print(weather_data.head())
DATE PRCP TMAX TMIN RAIN 0 1948-01-01 0.47 51 42 True 1 1948-01-02 0.59 45 36 True 2 1948-01-03 0.42 45 35 True 3 1948-01-04 0.31 45 34 True 4 1948-01-05 0.17 45 32 True
Creating a Plot
Now, let’s create a simple Matplotlib Scatterplot, with a few different variables we want to visualize:
PRCP = weather_data['PRCP'] TMAX = weather_data['TMAX'] TMIN = weather_data['TMIN']
Now, we’ll construct a scatter plot between the minimum temperature and precipitation and show() it using Matplotlib’s PyPlot:
plt.scatter(TMIN, PRCP) plt.show()
The graph that we have produced is interpretable, but it is looking a little plain. Let’s try customizing it. We want to customize the background of our plot using a couple of different methods.
Change Plot Background in Matplotlib
Now, let’s go ahead and change the background of this plot. We can do this with two different approaches. We can change the color of the face, which is currently set to white . Or, we can input a picture using imshow() .
Change Axes Background in Matplotlib
Let’s first change the color of the face. This can either be done with the set() function, passing in the face argument and its new value, or via the dedicated set_facecolor() function:
ax = plt.axes() ax.set_facecolor("orange") # OR ax.set(facecolor = "orange") plt.scatter(TMIN, PRCP) plt.show()
Either of these approaches produces the same result, as they both call on the same function under the hood.
Change Figure Background in Matplotlib
If you would like to set the background for the figure and need an axes to be transparent, this can be done with the set_alpha() argument when you create the figure. Let’s create a figure and an axes object. Of course, you can also use the set() function, and pass the alpha attribute instead.
The color of the entire figure will be blue and we will initially set the alpha of the axes object to 1.0 , meaning fully opaque. We color the axes object orange, giving us an orange background within the blue figure:
fig = plt.figure() fig.patch.set_facecolor('blue') fig.patch.set_alpha(0.6) ax = fig.add_subplot(111) ax.patch.set_facecolor('orange') ax.patch.set_alpha(1.0) plt.scatter(TMIN, PRCP) plt.show()
Now let’s see what happens when we adjust the alpha of the axes subplot down to 0.0 :
fig = plt.figure() fig.patch.set_facecolor('blue') fig.patch.set_alpha(0.6) ax = fig.add_subplot(111) ax.patch.set_facecolor('orange') ax.patch.set_alpha(0.0) plt.scatter(TMIN, PRCP) plt.show()
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Notice that the background of the plot itself is transparent now.
Add Image to Plot Background in Matplotlib
If you would like to use an image as the background for a plot, this can be done by using PyPlot’s imread() function. This function loads an image into Matplotlib, which can be displayed with the function imshow() .
In order to plot on top of the image, the extent of the image has to be specified. By default, Matplotlib uses the upper left corner of the image as the image’s origin. We can give a list of points to the imshow() function, specifying what region of the image should be displayed. When combined with subplots, another plot can be inserted on top of the image.
Let’s use an image of rain as the background for our plot:
img = plt.imread("rain.jpg") fig, ax = plt.subplots() ax.imshow(img, extent=[-5, 80, -5, 30]) ax.scatter(TMIN, PRCP, color="#ebb734") plt.show()
The extent argument takes in additional arguments in this order: horizontal_min , horizontal_max , vertical_min , vertical_max ).
Here, we’ve read the image, cropped it and showed it on the axes using imshow() . Then, we’ve plotted the scatter plot with a different color and shown the plot.
Conclusion
In this tutorial, we’ve gone over several ways to change a background of a plot using Python and Matplotlib.
If you’re interested in Data Visualization and don’t know where to start, make sure to check out our bundle of books on Data Visualization in Python:
Data Visualization in Python
Become dangerous with Data Visualization
✅ 30-day no-question money-back guarantee
✅ Updated regularly for free (latest update in April 2021)
✅ Updated with bonus resources and guides
Data Visualization in Python with Matplotlib and Pandas is a book designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and allow them to build a strong foundation for advanced work with theses libraries — from simple plots to animated 3D plots with interactive buttons.
It serves as an in-depth, guide that’ll teach you everything you need to know about Pandas and Matplotlib, including how to construct plot types that aren’t built into the library itself.
Data Visualization in Python, a book for beginner to intermediate Python developers, guides you through simple data manipulation with Pandas, cover core plotting libraries like Matplotlib and Seaborn, and show you how to take advantage of declarative and experimental libraries like Altair. More specifically, over the span of 11 chapters this book covers 9 Python libraries: Pandas, Matplotlib, Seaborn, Bokeh, Altair, Plotly, GGPlot, GeoPandas, and VisPy.
It serves as a unique, practical guide to Data Visualization, in a plethora of tools you might use in your career.
Change Background Color of Plot in Matplotlib
In this tutorial, we’ll look at how to change the background color of plots in matplotlib. Note that, the background color here means the background color of the region bounded by the axes. Also referred to as the axes face color.
How to change background color in matplotlib?
To change the background color of matplotlib plots, you can use the set_facecolor() function of the axes object of the plot. You can also set a global face color for all plots using rcParams . (See the syntax and examples below). The following is the syntax:
📚 Discover Online Data Science Courses & Programs (Enroll for Free)
Introductory ⭐
Intermediate ⭐⭐⭐
🔎 Find Data Science Programs 👨💻 111,889 already enrolled
Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.
# set the face color of an axes object ax.set_facecolor('orange') # set the face color globally for all axes objects plt.rcParams.update()
The above syntax assumes matplotlib.pyplot is imported as plt .
In the above syntax, we first have the code to set the face color of a specific axes object and then we have the code to set the face color globally for all plots.
Examples
Let’s look at some examples of using the above syntax to change the background color in matplotlib plots. First, we’ll create a simple matplotlib line plot and see the default face color of the plot.
import matplotlib.pyplot as plt # reset the plot configurations to default plt.rcdefaults() # number of employees of A emp_count = [3, 20, 50, 200, 350, 400] year = [2014, 2015, 2016, 2017, 2018, 2019] # plot a line chart fig, ax = plt.subplots() ax.plot(year, emp_count) # set axis titles ax.set_xlabel("Year") ax.set_ylabel("Employees") # set chart title ax.set_title("Employee Growth at A") plt.show()
You can see that in the above plot the default face color is white. Let’s go ahead and add a custom face color to our plot. There are multiple ways to add custom axes face color to our plots – You can set a custom face color individually for your axes objects or you can add a default face color for all the plots using rcParams.
1. Custom face color for axes object
To set the face color of individual plots, use the axes object’s set_facecolor() function.
# plot a line chart with custom axes face color fig, ax = plt.subplots() ax.plot(year, emp_count) # set axis titles ax.set_xlabel("Year") ax.set_ylabel("Employees") # set chart title ax.set_title("Employee Growth at A") # set axes facecolor ax.set_facecolor("orange") plt.show()
In the above example, we set the face color of the ax object to “orange” and you can see that the resulting plot has an orange background in region bounded by the axes.
2. Set a default axes face color for all plots
You can also set the default axes face color to be used in all your plots by updating the rcParams configurations.
# reset the plot configurations to default plt.rcdefaults() # set the axes color glbally for all plots plt.rcParams.update() # plot a line chart fig, ax = plt.subplots() ax.plot(year, emp_count) # set axis titles ax.set_xlabel("Year") ax.set_ylabel("Employees") # set chart title ax.set_title("Employee Growth at A") plt.show()
Note that first, we used the rcdefaults() function to reset the matplotlib configurations to their defaults, and then went ahead to update our default axes face color to “lightblue”. The resulting plot has a “lightblue” axes face color.
Since we have updated the default axes face color, all the following plots will have the same axes face color (“lightblue” in our case). Let’s create a different plot to see this in action.
# plot a line chart fig, ax = plt.subplots() ax.scatter(year, emp_count) # set axis titles ax.set_xlabel("Year") ax.set_ylabel("Employees") # set chart title ax.set_title("Employee Growth at A") plt.show()
The above scatter plot has “lightblue” axes face color.
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having matplotlib version 3.2.2
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
How to change background color in Matplotlib with Python
Actually, we are going to change the background color of any graph or figure in matplotlib with python. We have to first understand how this work, as there is a method to change the background color of any figure or graph named as “ set_facecolor “.
Changing the background color of the graph in Matplotlib with Python
Let’s understand with some examples:-
- In 1 st example, we simply draw the graph with the default background color(White).
- And in 2 nd example, we draw the graph and change the background color to Grey.
- Finally, in 3 rd example, we draw the graph and change the background color to Orange.
import matplotlib.pyplot as plt import numpy as np # Creating numpy array X = np.array([1,2,3,4,5]) Y = X**2 # Setting the figure size plt.figure(figsize=(10,6)) plt.plot(X,Y) plt.show()
In the above example, the background color of the graph is default(White), so first, we need to import two python module “matplotlib” and “numpy” by writing these two lines:-
Now, we created the numpy array and stored this in a variable named X and established the relation between X and Y. Then, we set the size of figure with method “plt.figure(figsize=(10,6))” where width=10 and height=6 and then we plotted the graph by “plt.plot(X,Y)“.
import matplotlib.pyplot as plt import numpy as np # Creating the numpy array X = np.array([1,2,3,4,5]) Y = X**2 # Setting the figure size plt.figure(figsize=(10,6)) ax = plt.axes() # Setting the background color ax.set_facecolor("grey") plt.plot(X,Y) plt.show()
In this example we are doing the same thing as in the above example, the only thing we did different from the above example is using “ax.set_facecolor(“grey”)” to change the background color of graph or figure.
import matplotlib.pyplot as plt import numpy as np # Creating the numpy array X = np.array([1,2,3,4,5]) Y = X**2 # Setting the figure size plt.figure(figsize=(10,6)) ax = plt.axes() # Setting the background color ax.set_facecolor("orange") plt.plot(X,Y) plt.show()
In this example, we only changed the background color to Orange, and the rest explanation is the same as explained above.
You may also read these articles:-