How to control text in Matplotlib

Key takeaways:

  • Matplotlib allows extensive customization of text in plots through position and font controls.

  • The ax.text() function is used to specify the location, alignment, orientation, and style of text.

  • Location control involves setting x and y coordinates for text placement.

  • Alignment can be adjusted both horizontally and vertically using the ha and va parameters.

  • The orientation of text can be set using the rotation parameter.

  • Font properties include family, style, variant, weight, and size, enabling precise typography.

  • Matplotlib supports LaTeX formatting for advanced text styling.

  • Customizing text enhances the clarity and visual appeal of data visualizations.

Matplotlib provides users with an extensive toolkit for fine-tuning text in plots and figures in Matplotlib. Although these options can be set as runtime configuration parameters. In this Answer, we will use Matplotlib’s axis.text() attribute to manipulate text in the figures. Text tools in Matplotlib can be categorized into two portions:

  • Position control: Position-related options let us set the location, alignment, and orientation of text.

  • Font control: Font options let us change the style and font properties of text.

Although there are specific ways of controlling text for specific components of a figure, i.e., x-labels, y-labels, and titles, these two options, which we will discuss here, provide the users with overall control over the text. By understanding these two options, you can make titles, labels, annotations, and more according to your design needs.

Position control

Adding text to any figure requires the first choice of where and in what orientation to place it. We will split the position control into three subcomponents, which are discussed below.

Location control

By location, we refer to the point where we want our text box to be placed on the plot. The axis.text() function deals with the text to be displayed and the point where it should appear on the plot. It has three compulsory input arguments:

  1. x-location: This parameter dictates the starting location for text in the x-axis.

  2. y-location: This parameter dictates the starting location for text in the y-axis.

  3. Text: The text to be added should be in the string format.

The following code demonstrates how to do it.

import matplotlib.pyplot as plt
# Create a simple plot
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
# Add text to the plot with specified location
ax.text(3, 2.7, 'Sample Text')
  • Line 8: Calling the ax.text() function and providing the three compulsory input arguments.

Alignment control

By the three compulsory arguments of the axis.text() function, a text box is defined by Matplotlib, and the provided text is placed in it. However, this is not where it ends. This function also provides us with the option to choose the horizontal and vertical alignment of the text inside the defined text box. Let’s briefly discuss these options:

  • Horizontal alignment: Horizontal alignment instructions can be sent through the ha parameter. Matplotlib offers three options for text alignment in the horizontal direction: left, right, and center.

  • Vertical alignment: Vertical alignment instructions can be sent through the va parameter. Matplotlib offers five options for text alignment in the vertical direction: top, bottom, center, baseline, and center_baseline.

The following code demonstrates how to do it.

import matplotlib.pyplot as plt
# Create a simple plot
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
# Add text to the plot with specified properties
ax.text(3, 2.7, 'Sample Text',
ha='center', # Horizontal alignment ('center' in this case)
va='bottom') # Vertical alignment ('bottom' in this case)
  • Line 9: Define the horizontal alignment preference with the help of ha input argument.

  • Line 10: Define the vertical alignment preference with the help of va input argument.

Orientation control

Other than the alignment and location of the text in figures, Matplotlib takes a step ahead and allows us to set the orientation of the text. We can do this by providing the rotation parameter in the axis.text() attribute. The rotation parameter can be set to horizontal or vertical for simple orientation or a float value can also be provided, defining the angle of orientation in degrees.

The following code demonstrates how to do it.

import matplotlib.pyplot as plt
# Create a simple plot
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
# Add text to the plot with specified properties
ax.text(3, 2.7, 'Sample Text',
ha='center', # Horizontal alignment ('center' in this case)
va='bottom', # Vertical alignment ('bottom' in this case)
rotation=45) # Text rotation angle (45 degrees in this case)

Line 11: Specify the rotation angle using the rotation input argument.

Font control

There are a total of five functional properties provided by Matplotlib that can be used for font setting. Let’s have a look at these font-related properties:

  1. Font family: The family parameter sets the default font family for text. The options available for font categories are: serif, sans-serif, cursive, fantasy, and monospace. For each category, a specific font can also be chosen.

  2. Font style: The style parameter defines the default font style as normal, italic, or oblique. If the italic is unavailable in the font family chosen, oblique serves as a graceful fallback.

  3. Font variant: The variant parameter opts for normal or small-caps as the default font variant. Compared to TrueType fonts, small-caps emulates a font size of smaller, about 83% of the current font size.

  4. Font weight: The weight parameter specifies the default font weight. Available options are normal, bold, bolder, lighter, or numerical values ranging from 100 to 900. normal corresponds to 400, while bold equates to 700 weight.

  5. Font size: The size parameter sets the default font size (measured in points). The default size typically stands at 10 points.

The following code demonstrates how to do it.

import matplotlib.pyplot as plt
# Create a simple plot
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
# Add text to the plot with specified properties
ax.text(3, 2.7, 'Sample Text',
ha='center', # Horizontal alignment ('center' in this case)
va='bottom', # Vertical alignment ('bottom' in this case)
rotation=45, # Text rotation angle (45 degrees in this case)
family='serif', # Font family
style='italic', # Font style ('italic' in this case)
variant='small-caps',# Font variant ('small-caps' in this case)
weight='bold', # Font weight ('bold' in this case)
size=14) # Font size (14 points in this case)
  • Line 12: Specify the font family using the family input argument.

  • Line 13: Specify the font style using the style input argument.

  • Line 14: Specify the font variant using the variant input argument.

  • Line 15: Specify the font weight using the weight input argument.

  • Line 16: Specify the font size using the size input argument.

The font-changing options we discussed here provide the users with overall control over the text. Matplotlib extends font sizing options to axis labels, tick labels, legend text, and figure titles for finer control. Options can be applied to each text element individually through additional parameters like axes.labelsize, xtick.labelsize, ytick.labelsize, legend.fontsize, and figure.titlesize. Matplotlib also supports LaTeX formatting.

Conclusion

In conclusion, Matplotlib provides robust tools for customizing text in plots, enabling users to control position and font properties effectively. The ax.text() function allows for precise adjustments in location, alignment, orientation, and styling, enhancing the visual appeal and clarity of visualizations. With support for LaTeX formatting and extensive font options, users can create professional-quality figures that effectively communicate data insights. Mastering these text control features significantly improves the readability and impact of data presentations.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How can we put text on a Matplotlib plot?

To put text on a Matplotlib plot, use the ax.text(x, y, 'your text') function, where x and y define the text position.


How do we control font size in Matplotlib?

To control font size in Matplotlib, specify the size parameter in the ax.text() function or set plt.rcParams['font.size'] globally.


How do we underline text in Matplotlib?

To underline text in Matplotlib, you can use LaTeX formatting by setting usetex=True in the rc settings and using r'$\underline{your text}$' in the text string.


How can we print text in Matplotlib?

To print text in Matplotlib, you can use the print() function in Python, or for displaying text in the plot, use the ax.text() or plt.text() functions.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved