Author avatar

Vivek Kumar

Working with Text

Vivek Kumar

  • Apr 10, 2019
  • 9 Min read
  • 28 Views
  • Apr 10, 2019
  • 9 Min read
  • 28 Views
Data
matplotlib

Introduction

In this guide, you will learn about embedding and taking control of the text data in Matplotlib figures.

By the end of this guide, you will be able to code on the following topics:

  1. Defining text in Matplotlib plots
  2. Working with text properties and layouts
  3. Creating annotations
  4. Writing mathematical expressions

The Baseline

Throughout this guide we will be using the following libraries:

Syntax

1
2
3
4
5
# Importing necessary libraries
import numpy as np
import scipy.stats as stats
import matplotlib as mpl
import matplotlib.pyplot as plt
python

Defining Text in Matplotlib Plots

When we talk about visualization, we may think of colors and labels. This portion of the guide will specifically focus on three topics:

  1. Labeling basic text on the plot
  2. Handling the ticks and tick labels
  3. Labeling legend

1. Labeling Basic Text on the Plot

To start with the basic text labeling, let us take some random data and label the figure title, the axes title, the x-label, and the y-label of the plot:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# Setting the figure size
plt.figure(figsize=(8, 5))

# Initializing the data
np.random.seed(42)
x, y = 100 * np.random.rand(2, 1000)

# Plotting
plt.plot(x, y, 'go', alpha=0.2)  

# Labelling the Figure title
plt.suptitle('Random data',                  # Name
            horizontalalignment='center',  # Location            
            weight='extra bold',                # Size of text
            fontsize=20,                           # Font size
            fontfamily='monospace',        # Font family
            color='Green')                       # Color

# Labelling the Axes title
plt.title('generated using NumPy',   # Name
          loc='center',                           # Location
          weight='ultralight',                 # Size of text
          fontsize=16,                          # Font size
          fontfamily='serif',                  # Font family
          color='Green')                      # Color


# Labelling the x and y axis
plt.xlabel('The X-label', fontsize=16, color='Green')

plt.ylabel('The Y-label', fontsize=16, color='Green')

# Displaying the plot
plt.show()
python

Basic

2. Handling the Ticks and Tick Labels

In the previous figure, we have labeled the figure and axes title along with X and Y labels. Now, let us try to learn how we can perform changes to the X and Y ticks, tick labels, and axes.

To achieve this, we have to utilize a few methods, such as rc, xticks, yticks, and tick_params. Let us continue with the previous scenario:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# Setting the figure size
plt.figure(figsize=(8, 5))

# Initializing the data
np.random.seed(42)
x, y = 100 * np.random.rand(2, 1000)

# Changing the color of Axes 
mpl.rc('axes', edgecolor='Green')

# Plotting
plt.plot(x, y, 'go', alpha=0.2)  

# Labelling the Figure title
plt.suptitle('Random data',                # Name
            horizontalalignment='center',  # Location            
            weight='extra bold',           # Size of text
            fontsize=20,                   # Font size
            fontfamily='monospace',        # Font family
            color='Green')                 # Color

# Labelling the Axes title
plt.title('generated using NumPy',         # Name
          loc='center',                    # Location
          weight='ultralight',             # Size of text
          fontsize=16,                     # Font size
          fontfamily='serif',              # Font family
          color='Green')                   # Color

# Labelling the x and y axis
plt.xlabel('The X-label', fontsize=16, color='Green')

plt.ylabel('The Y-label', fontsize=16, color='Green')

# Setting the different tick labels
plt.xticks(np.linspace(0, 100, 6),               # Location of new ticks
           ['X1', 'X2', 'X3', 'X4', 'X5', 'X6'], # New tick names
           color='Green')                        # Color

plt.yticks(np.linspace(0, 100, 6),               # Location of new ticks
           ['Y1', 'Y2', 'Y3', 'Y4', 'Y5', 'Y6'], # New tick names
           color='Green')                        # Color

# Changing the color of x and y ticks
plt.tick_params(axis='both', color='Green')

# Displaying the plot
plt.show()
python

Ticks

3. Labeling the Legend

A legend helps in describing the list of symbols or markers used in a plot. Let us take two sets of sample data and learn to label the legend for each of the datasets:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Setting the figure size
plt.figure(figsize=(8, 5))

# Initializing the data
x1 = np.arange(0.0, 5.0, 0.1)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
x2 = np.arange(0.0, 5.0, 0.02)
y2 = np.cos(2 * np.pi * x2)

# Plotting
plt.plot(x1, y1, 'o-', label = "Signal 1")
plt.plot(x2, y2, '.-', label = "Signal 2")

# Extending x and y axis limits
plt.axis([0, 5.2, -1, 1.5])

# Labelling the legend
plt.legend(loc = 'best',          # Best adjust according to figure shape
              shadow = True,       # Displaying the legend shadow
              fontsize = 'medium', # Font size
              ncol=2,                 # Number of columns in the box
              framealpha = 0.5)    # Transperancy factor

# Labelling the title
plt.title('A Figure with a Legend Box', weight='bold', fontsize=18)

# Displaying the plot
plt.show()
python

Legend

Working with Text Properties and Layouts

We have already implemented many of the text properties in the above topic, for example, fontsize, fontfamily, weight, etc. Now, let us learn the most usable method, matplotlib.pyplot.text. With the matplotlib.pyplot.text, we can control all the text properties and text layouts. Given is an example which shows various usage of matplotlib.pyplot.text:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Setting the figure size
plt.figure(figsize=(10, 5))

# Creating a figure with defined axis
plt.scatter(0.535, 0.49, s=3700, facecolors='none', edgecolors='k')
plt.axis([0, 1, 0, 1])

# Labelling the texts
plt.text(0.1, 0.9, 'This text forms first segment of the plot', 
         ha='left', va='top', rotation=45, fontsize=16, color='Green')

plt.text(0.5, 1, 'This text forms second segment of the plot', 
         ha='left', va='top', rotation=-45, fontsize=16, color='Red')

plt.text(0.23, 0.2, 'This text forms third segment of the plot', 
         fontsize=16, color='Blue')

plt.text(0.5, 0.45, 'Hi!', 
         fontsize=30, color='k')

# Displaying the plot
plt.show()
python

Text

Creating Annotations

Having control over text by using matplotlib.pyplot.text method is quite handy, however, sometimes a situation can arise when you cannot write a text at the desired coordinates because that may result in the loss of background information. Therefore, annotations are available in Matplotlib through which we can connect the text to a desired coordinate point using lines.

Let us take an example to learn the implementation of annotations using matpliotlib.pyplot.annotate:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Setting the figure size
plt.figure(figsize=(10, 5))

# Initializing the data
np.random.seed(42)
x1, y1 = 10*np.random.rand(2, 1000)

x2 = np.arange(0.0, 10.0, 0.1)
y2 = 10*np.cos(2 * np.pi * x2) * np.exp(-x2)

# Plotting
plt.plot(x1, y1, 'ro', alpha=0.1) 
plt.plot(x2, y2, 'cs', x2, y2, 'g-')

# Performing annotation
plt.annotate('Coordinate (1, 3.5)', xy=(1, 3.5), xytext=(4, -4),
            arrowprops=dict(arrowstyle="fancy",facecolor='Orange'), 
            weight='bold', fontsize=16)

# Labelling the title
plt.title('Labelling annotation', weight='bold', fontsize=20)

# Displaying the plot
plt.show()
python

annot

In the above figure, we wanted to mention a label for the coordinate (1, 3.5) but not on the red points. Therefore, in similar cases, always use matplotlib.pyplot.annotate method to use an arrow as a bridge between the coordinate and the text.

Writing Mathematical Expressions

In the machine learning and statistics domain, creating a plot and writing mathematical expressions in the plot are inseparable. Therefore, let us learn to write mathematical expressions in the plot text. This can be achieved using the latex writing system. Let us plot a normal distribution graph with zero-mean, unit standard deviation, and mention the mathematical symbols on the plot:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Setting the figure size
plt.figure(figsize=(10, 5))

# Initializing the data
mu = 0
variance = 1
sigma = np.sqrt(variance)
val = np.linspace(mu - 3 * sigma, mu + 3 * sigma, 100)

# Plotting
plt.plot(x, stats.norm.pdf(val, mu, sigma))

# Writing expressions for mean and standard deviation
plt.text(0.7, 0.35, r'$\mu=0$' + '\n' + '$\sigma=1$', fontsize=15)

# Labelling the title
plt.title('Writing mathematical expressions', weight='bold', fontsize=20)

# Displaying the plot
plt.show()
python

math

Conclusion

In this guide you have learned about the basics of text labeling with its properties and layouts, marking annotations, and writing mathematical expressions in the plot.

To learn more on Matplotlib you can refer the following guides:

0