Making use of text and font properties

You already learned how to annotate the plot by adding legends, but sometimes we want more with text. This recipe will explain and demonstrate more features of text manipulation in matplotlib, giving a powerful toolkit for even advanced typesetting needs.

We will not cover LaTeX support in this recipe, as there is a recipe named Rendering text with LaTeX in this chapter.

Getting ready

We start with listing of the most useful set of functions that matplotlib offers. Most of the functions are available via pyplot module's interface, but we map their origin function here to allow you to explore more if a particular text feature is not covered in this recipe.

Basic text manipulations and their mapping in matplotlib OO API is presented in the following table:

matplotlib.pyplot

Matplotlib API

Description

text

matplotlib.axes.Axes.text

Adds text to the axes at the location specified by (x, y). Argument fontdict allows us to override generic font properties, or we can use kwargs to override a specific property.

xlabel

matplotlib.axes.Axes.set_xlabel

Sets the label for the x axis. Specifies the spacing between the label and the x axis in accordance with labelpad.

ylabel

matplotlib.axes.Axes.set_ylabel

Similar to xlabel, but intended for the y axis.

title

matplotlib.axes.Axes.set_title

Sets the title for the axes. Accepts all the usual text properties such as fontdict and kwargs.

suptitle

matplotlib.figure.Figure.suptitle

Adds a centered title to the figure. Accepts all the usual text properties via kwargs. Uses figure coordinates.

figtext

matplotlib.figure.Figure.text

Puts text anywhere on the figure. The location is defined using (x,y), using figure's normalized coordinates. Override font properties using fontdict, but also support kwargs to override any text-related property.

The base class for text storing and drawing inside windows or data coordinates is the matplotlib.text.Text class. It supports the definition of the location of text objects as well as a range of properties that we can define, to tune how our strings are going to appear on a figure or a window.

The font properties supported by the matplotlib.text.Text instances are:

Property

Values

Description

family

'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'

Specifies the font name or font family. If this is a list, then it is ordered by priority, so the first matched name will be used.

size or fontsize

12, 10,... or 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'

Specifies the size in relative or absolute points or specifies the relative size as a size string.

style or fontstyle

'normal', 'italic', 'oblique'

Specifies the font style as a string.

variant

'normal', 'small-caps'

Specifies the font variant.

weight or fontweight

0-1000 or 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'

Specifies the font weight or using a specific weight string. Font weight is defined as the thickness of character outline relative to its height.

stretch or fontstretch

0-1000 or 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'

Specifies the stretch of the font. Stretch is defined as horizontal condensation or expansion. This property is not currently implemented.

fontproperties

-

Defaults to the matplotlib.font_manager.FontProperties instance. This class stores and manages font properties as described in W3CCSSLevel1 specification at http://www.w3.org/TR/1998/REC-CSS2-19980512/.

We can also specify the background box that will contain the text, and which can be further specified in color, borders, and transparency.

The basic text color is read from rcParams['text.color'], if not specified on the current instance, of course.

Specified text can also be aligned according to visual needs. There are the following alignment properties:

  • horizontalalignment or ha: This allows alignment of text horizontally to center, left, and right.
  • verticalalignment or va: The allowed values for this are center, top, bottom, and baseline.
  • multialignment: This allows alignment of text strings that span multilines. The allowed values are left, right, and center.

How to do it...

So far all is good, but we have a hard time visualizing all these variations in the fonts we can create. So, this is going to illustrate what we can do. In the next code, we will perform the following steps:

  1. List all the possible properties we want to vary on the font.
  2. Iterate over the first set of variations: font family and size.
  3. Iterate over the second set of variations: weight and style.
  4. Render text samples for both the iterations and print the variation combination as a text on the plot.
  5. Remove axes from the figure, as they serve no purpose.

The following is the code:

importmatplotlib.pyplot as plt
frommatplotlib.font_manager import FontProperties

# properties:
families = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace']
sizes  = ['xx-small', 'x-small', 'small', 'medium', 'large',
         'x-large', 'xx-large']
styles  = ['normal', 'italic', 'oblique']
weights = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
variants = ['normal', 'small-caps']

fig = plt.figure(figsize=(9,17))
ax = fig.add_subplot(111)
ax.set_xlim(0,9)
ax.set_ylim(0,17)
   # VAR: FAMILY, SIZE
y = 0
size = sizes[0]
style = styles[0]
weight = weights[0]
variant = variants[0]

forfamily in families:
    x = 0
    y = y + .5
for size in sizes:
        y = y + .4
sample = family + " " + size
ax.text(x, y, sample, family=family, size=size,
style=style, weight=weight, variant=variant)
# VAR: STYLE, WEIGHT
y = 0
family = families[0] 
size = sizes[4]
variant = variants[0]

for weight in weights:
    x = 5
    y = y + .5
for style in styles:
        y = y + .4
sample = weight + " " + style
ax.text(x, y, sample, family=family, size=size,
style=style, weight=weight, variant=variant)

ax.set_axis_off()
plt.show()

The preceding code will produce the following screenshot:

How to do it...

How it works...

The code is really straightforward, as we just iterate twice over tuples of properties printing their values.

The only trick employed here is the positioning of text on the figure canvas, as that allows us to have a nice layout of text samples we can easily compare.

Keep in mind that the default font matplotlib will use is dependent on the operating system you are running, so the preceding screenshot might look slightly different. This screenshot was rendered using standard Ubuntu 13.04 installed fonts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.124.21