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 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
haandvaparameters.The orientation of text can be set using the
rotationparameter.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:
x-location: This parameter dictates the starting location for text in the x-axis.
y-location: This parameter dictates the starting location for text in the y-axis.
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 plotfig, ax = plt.subplots()ax.plot([1, 2, 3, 4], [1, 4, 2, 3])# Add text to the plot with specified locationax.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
haparameter. Matplotlib offers three options for text alignment in the horizontal direction:left,right, andcenter.Vertical alignment: Vertical alignment instructions can be sent through the
vaparameter. Matplotlib offers five options for text alignment in the vertical direction:top,bottom,center,baseline, andcenter_baseline.
The following code demonstrates how to do it.
import matplotlib.pyplot as plt# Create a simple plotfig, ax = plt.subplots()ax.plot([1, 2, 3, 4], [1, 4, 2, 3])# Add text to the plot with specified propertiesax.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
hainput argument.Line 10: Define the vertical alignment preference with the help of
vainput 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 plotfig, ax = plt.subplots()ax.plot([1, 2, 3, 4], [1, 4, 2, 3])# Add text to the plot with specified propertiesax.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:
Font family: The
familyparameter sets the default font family for text. The options available for font categories are:serif,sans-serif,cursive,fantasy, andmonospace. For each category, a specific font can also be chosen.Font style: The
styleparameter defines the default font style asnormal,italic, oroblique. If theitalicis unavailable in the font family chosen,obliqueserves as a graceful fallback.Font variant: The
variantparameter opts fornormalorsmall-capsas the default font variant. Compared to TrueType fonts,small-capsemulates a font size ofsmaller, about 83% of the current font size.Font weight: The
weightparameter specifies the default font weight. Available options arenormal,bold,bolder,lighter, or numerical values ranging from 100 to 900.normalcorresponds to 400, whileboldequates to 700 weight.Font size: The
sizeparameter 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 plotfig, ax = plt.subplots()ax.plot([1, 2, 3, 4], [1, 4, 2, 3])# Add text to the plot with specified propertiesax.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 familystyle='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
familyinput argument.Line 13: Specify the font style using the
styleinput argument.Line 14: Specify the font variant using the
variantinput argument.Line 15: Specify the font weight using the
weightinput argument.Line 16: Specify the font size using the
sizeinput 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?
How do we control font size in Matplotlib?
How do we underline text in Matplotlib?
How can we print text in Matplotlib?
Free Resources