How to Set Plot Background Color in Matplotlib?
Prerequisites:
From the below figure one can infer that a plot consists of X-axis, Y-axis, plot title and the axes. By default, the color of the plot is white. If we have to set the background color of the plot so that our plot looks beautiful, we have to make the axes object, by using axes() attribute after plotting the graph.
Approach:
- Import module
- Load or create data
- Plot a regular graph
- Create axes object
- Set attribute set_facecolor() to the required color. This attribute accepts both name or color code of the color
Follow the given examples to understand better.
Example: Default color plot
Python
import matplotlib.pyplot as plt
student_marks = [ 50 , 60 , 70 , 80 , 90 ]
student_grade = [ 'B' , 'B' , 'B+' , 'B+' , 'A' ]
plt.plot(student_marks, student_grade)
plt.xlabel( "student_marks" , fontweight = 'bold' )
plt.ylabel( "student_grade" , fontweight = 'bold' )
plt.title( "Student Marks v/s Student Grade" )
plt.show()
|
Output:
Example 2 : Setting background color to yellow
Python
import matplotlib.pyplot as plt
student_marks = [ 50 , 60 , 70 , 80 , 90 ]
student_grade = [ 'B' , 'B' , 'B+' , 'B+' , 'A' ]
plt.plot(student_marks, student_grade)
plt.xlabel( "student_marks" , fontweight = 'bold' )
ax = plt.axes()
ax.set_facecolor( "yellow" )
plt.ylabel( "student_grade" , fontweight = 'bold' )
plt.title( "Student Marks v/s Student Grade" )
plt.show()
|
Output:
Example 3: Setting background color to violet
Python
import matplotlib.pyplot as plt
import numpy as np
x = np.arange( 0 , 10 , . 1 )
y = np.sin(x)
plt.plot(x, y)
plt.xlabel( "X" )
ax = plt.axes()
ax.set_facecolor( "violet" )
plt.ylabel( 'sin(x)' )
plt.show()
|
Output:
Setting Outer and Inner color of plot
We can also set the color of the outer portion of the plot. To set both the color for plot background and for outer portion of the plot the only change we have to do in our code is that we have to add plt.figure(faceccolor=’color’) before plotting the graph.
Example 1:
Python
import matplotlib.pyplot as plt
import numpy as np
x = np.arange( 0 , 10 , . 1 )
y = np.sin(x)
plt.figure(facecolor = 'yellow' )
plt.plot(x, y)
plt.xlabel( "X" )
ax = plt.axes()
ax.set_facecolor( "violet" )
plt.ylabel( 'sin(x)' )
plt.show()
|
Output:
Example 2: Setting plot color using html color codes
Python
import matplotlib.pyplot as plt
import numpy as np
x = np.arange( 0 , 10 , . 1 )
y = np.sin(x)
plt.figure(facecolor = '#94F008' )
plt.plot(x, y)
plt.xlabel( "X" )
ax = plt.axes()
ax.set_facecolor( "#1CC4AF" )
plt.ylabel( 'sin(x)' )
plt.show()
|
Output:
Conclusion
In this tutorial, we’ve gone over several ways to change a background of a plot using Python and Matplotlib.
Last Updated :
13 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...