Adding Title to the Plot
Choosing a Title
A good plot includes a clear and informative title. Generic titles like "Line plot" or "Scatter plot" lack context and fail to convey the purpose of the visualization. A better example is "New York Average Monthly Temperatures (2022)", which specifies the data content, location, and time periodβkey details that provide clarity.
The following shows how to set a plot title using matplotlib
:
import matplotlib.pyplot as plt programming_languages = ['Python', 'Java', 'C#', 'C++'] shares = [40, 30, 17, 13] plt.bar(programming_languages, shares, color=['b', 'green', 'red', 'yellow']) # Setting the plot title plt.title('Percentage of users of programming languages') plt.show()
Title Customization
The title is set using the plt.title()
function with the title text passed as a string. Besides the main label
parameter, the font size can be modified via the fontsize
argument (default is 10
), and the font color can be specified using the color
parameter. These are the primary options for customizing titles.
Another important parameter is loc
(location), which can take one of the values: center
(default), left
, and right
.
Let's now modify the title in our example:
import matplotlib.pyplot as plt programming_languages = ['Python', 'Java', 'C#', 'C++'] shares = [40, 30, 17, 13] plt.bar(programming_languages, shares, color=['b', 'green', 'red', 'yellow']) # Customizing the title appearance plt.title('Percentage of users of programming languages', loc='left', fontsize=7, color='indigo') plt.show()
The title is aligned to the left, with increased font size and a changed font color. These parameters are usually the main focus when customizing titles.
However, you can always refer to the title()
documentation for more information.
Swipe to start coding
The task is to create a title for a line plot of average yearly temperatures in Boston and Seattle.
- Use the correct function to set the title for the plot.
- Set the following title:
'Boston and Seattle average yearly temperatures'
. - Set the font size of the title to be
15
. - Set the location of the title to
right
.
Solution
Thanks for your feedback!