0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Set Title in Matplotlib: Simple Guide

To set a title in Matplotlib, use the plt.title() function and pass your title text as a string. This adds a title to the current plot, making it easier to understand the graph's purpose.
๐Ÿ“

Syntax

The basic syntax to set a title in Matplotlib is:

  • plt.title(label, fontdict=None, loc='center', pad=None, **kwargs)

Where:

  • label: The text string for the title.
  • fontdict: Optional dictionary to control font properties like size and color.
  • loc: Location of the title; can be 'left', 'center', or 'right'. Default is 'center'.
  • pad: Distance in points between the title and the plot.
  • **kwargs: Additional text properties like fontsize, color, weight.
python
plt.title('Your Title Here')
๐Ÿ’ป

Example

This example shows how to create a simple plot and set its title using plt.title(). It also demonstrates customizing the font size and color.

python
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 5, 8, 12, 7]

plt.plot(x, y)
plt.title('Sample Plot Title', fontsize=14, color='blue')
plt.show()
Output
A line plot with x values [1,2,3,4,5] and y values [10,5,8,12,7] appears with the title 'Sample Plot Title' in blue color above the plot.
โš ๏ธ

Common Pitfalls

Some common mistakes when setting titles in Matplotlib include:

  • Forgetting to call plt.show() to display the plot with the title.
  • Setting the title before creating the plot, which might cause confusion in complex scripts.
  • Using incorrect font property names or unsupported values in fontdict or kwargs.
  • Not specifying the location if you want the title aligned differently than center.
python
import matplotlib.pyplot as plt

# Wrong: Title set before plot (still works but less clear in complex code)
plt.title('Wrong Order')
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

# Right: Title set after plot
plt.plot([1, 2, 3], [4, 5, 6])
plt.title('Right Order')
plt.show()
Output
Two plots appear sequentially: first with title 'Wrong Order', second with title 'Right Order'. Both show the line plot but the second approach is clearer in code flow.
๐Ÿ“Š

Quick Reference

ParameterDescriptionExample
labelText for the title'My Plot Title'
fontsizeSize of the title fontfontsize=16
colorColor of the title textcolor='red'
locTitle alignment: 'left', 'center', 'right'loc='left'
padPadding between title and plot in pointspad=20
โœ…

Key Takeaways

Use plt.title('Your Title') to add a title to your Matplotlib plot.
Customize title appearance with fontsize, color, and loc parameters.
Set the title after creating the plot for clearer code.
Remember to call plt.show() to display the plot with the title.
Use the pad parameter to adjust space between title and plot if needed.