A plotting library
Adding Text in Plots
You already know how to add legends to charts, but what about other text, maybe in nonstandard parts of a plot? Listing 8 shows the simplest way to add the captions and annotations shown in Figure 6.
Listing 8
Inserting Text
01 import Matplotlib.pyplot as plt 02 import NumPy as np 03 04 t = np.arange(0., 50, 0.2) 05 06 07 plt.plot(t, (t**3)*np.cos(2*t)) 08 09 plt.title("Combination of trigonometric and power factors") 10 11 plt.text(1, 80000, r'$Function: (t^\mu)*cos(\sigma*t),\ with\ \mu = 3\ and\ \sigma = 2$') 12 13 plt.annotate('local maximum', xy=(19, 4100), xytext=(1, 45000), arrowprops=dict(facecolor='red', shrink=0.05)) 14 15 plt.savefig('text-in-plots.png')
![](/var/linux_magazin/storage/images/issues/2022/257/tutorial-matplotlib/figure-6/801541-1-eng-US/Figure-6_large.png)
Lines 11 and 13 of Listing 8 describe the function that generates the "local maximum" annotation shown in Figure 6. This syntax is relatively simple to describe: plt.annotate
takes as arguments the string to insert, its starting position (xytext
), the point where the arrow should end (xy
), and its style (arrowprops
). In line 11, plt.text
has even fewer arguments: just the coordinates where a string should be inserted and then the string itself. The string is enclosed by single quotes and dollar signs and preceded by an r
suffix, which means that what follows is "raw" text that uses LaTeX syntax and symbols (e.g., \mu
and \sigma
). Also note that in these strings blank spaces must be escaped to tell Python that they are actual spaces that should just be printed instead of separators of function arguments.
Categorical Charts
Another place in a plot where you might want arbitrary text instead of numbers or dates is on its Axes. In Matplotlib, this type of diagram is called a categorical chart. Figure 7 shows a categorical chart of how cats and dogs consider certain activities.
Unless you have lots of categories to display or other special needs, plotting categorical charts is easier than it appears. Listing 9 only needs three arrays of strings and five lines of code to create Figure 7. The activity
array lists all the activities, and the cat
and dog
arrays describe how those pets consider each activity (lines 3 to 5). The only critical part here is that each reaction of cats or dogs must be in the same position of the corresponding activity. That is, if playing
is the fifth element of the activity
array, and dogs are SUPER-HAPPY
only when playing, then SUPER-HAPPY
must be the fifth element of the dog
array and the only element with the SUPER-HAPPY
value. Then, all Matplotlib needs to plot everything correctly are the ax.plot
methods shown in lines 8 and 9, which take the two arrays as the lists of x and y values to use to find all the points of each plot.
Listing 9
Categorical Chart
01 import Matplotlib.pyplot as plt 02 03 activity = ["combing", "drinking", "feeding", "napping", "playing", "washing"] 04 cat = ["bored", "happy", "SUPER-HAPPY", "SUPER-HAPPY", "happy", "bored"] 05 dog = ["bored", "happy", "happy", "bored", "SUPER-HAPPY", "bored"] 06 07 fig, ax = plt.subplots() 08 ax.plot(activity, dog, label="dog") 09 ax.plot(activity, cat, label="cat") 10 ax.legend() 11 plt.title("Pet feelings vs pet activities") 12 plt.savefig('categorical-names.png')
Sankey Diagrams
A Sankey diagram [7] represents the flow of certain variables in or out of a system by depicting each flow's width proportional to its quantity. While this type of diagram is not useful for everyone, a Sankey diagram showcases Matplotlib's flexibility and might also be a lifesaver for those in the fields of energy management, manufacturing, and science. Figure 8 and its code in Listing 10 are another example provided, but not completely explained, by the official Matplotlib documentation [8].
Listing 10
Sankey Diagram
01 import Matplotlib.pyplot as plt 02 from Matplotlib.sankey import Sankey 03 04 Sankey(flows=[0.25, 0.15, 0.60, -0.20, -0.15, -0.05, -0.50, -0.10], labels=['', '', '', 'First', 'Second', 'Third', 'Fourth', 'Fifth'], orientations=[-1, 1, 0, 1, 1, 1, 0, -1]).finish() 05 plt.title("Did you know how easy it is to create diagrams like this?") 06 plt.savefig('sankey.png')
![](/var/linux_magazin/storage/images/issues/2022/257/tutorial-matplotlib/figure-8/801547-1-eng-US/Figure-8_large.png)
To draw a Sankey diagram, Matplotlib (or any other tool, for that matter) needs two things: a function, or object, that knows how to draw a Sankey diagram, and the parameters of each flow that enters or leaves the system. Listing 10 does just that by importing the Sankey function (line 2) and then telling Matplotlib to create and finish a Sankey object with the single long command in line 4. To do that, of course, each flow must be described by three parameters, namely the flow's intensity, orientation (i.e., if it enters or leaves the system), and an optional label. Lines 4 and 6 of Listing 10 pass this data passed to the Sankey object. As an example, the arrow pointing downward in Figure 8 (with a value of 0.1 and the label "Fifth") is the direct result of writing -0.10
, 'Fifth'
, and -1
in the last elements of the flows, labels, and orientation arrays (lines 4-6) passed to the Sankey object.
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters
Support Our Work
Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.
![Learn More](https://www.linux-magazine.com/var/linux_magazin/storage/images/media/linux-magazine-eng-us/images/misc/learn-more/834592-1-eng-US/Learn-More_medium.png)
News
-
NVIDIA Released Driver for Upcoming NVIDIA 560 GPU for Linux
Not only has NVIDIA released the driver for its upcoming CPU series, it's the first release that defaults to using open-source GPU kernel modules.
-
OpenMandriva Lx 24.07 Released
If you’re into rolling release Linux distributions, OpenMandriva ROME has a new snapshot with a new kernel.
-
Kernel 6.10 Available for General Usage
Linus Torvalds has released the 6.10 kernel and it includes significant performance increases for Intel Core hybrid systems and more.
-
TUXEDO Computers Releases InfinityBook Pro 14 Gen9 Laptop
Sporting either AMD or Intel CPUs, the TUXEDO InfinityBook Pro 14 is an extremely compact, lightweight, sturdy powerhouse.
-
Google Extends Support for Linux Kernels Used for Android
Because the LTS Linux kernel releases are so important to Android, Google has decided to extend the support period beyond that offered by the kernel development team.
-
Linux Mint 22 Stable Delayed
If you're anxious about getting your hands on the stable release of Linux Mint 22, it looks as if you're going to have to wait a bit longer.
-
Nitrux 3.5.1 Available for Install
The latest version of the immutable, systemd-free distribution includes an updated kernel and NVIDIA driver.
-
Debian 12.6 Released with Plenty of Bug Fixes and Updates
The sixth update to Debian "Bookworm" is all about security mitigations and making adjustments for some "serious problems."
-
Canonical Offers 12-Year LTS for Open Source Docker Images
Canonical is expanding its LTS offering to reach beyond the DEB packages with a new distro-less Docker image.
-
Plasma Desktop 6.1 Released with Several Enhancements
If you're a fan of Plasma Desktop, you should be excited about this new point release.