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')
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')
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.
News
-
Linux Kernel 6.13 Offers Improvements for AMD/Apple Users
The latest Linux kernel is now available, and it includes plenty of improvements, especially for those who use AMD or Apple-based systems.
-
Gnome 48 Debuts New Audio Player
To date, the audio player found within the Gnome desktop has been meh at best, but with the upcoming release that all changes.
-
Plasma 6.3 Ready for Public Beta Testing
Plasma 6.3 will ship with KDE Gear 24.12.1 and KDE Frameworks 6.10, along with some new and exciting features.
-
Budgie 10.10 Scheduled for Q1 2025 with a Surprising Desktop Update
If Budgie is your desktop environment of choice, 2025 is going to be a great year for you.
-
Firefox 134 Offers Improvements for Linux Version
Fans of Linux and Firefox rejoice, as there's a new version available that includes some handy updates.
-
Serpent OS Arrives with a New Alpha Release
After months of silence, Ikey Doherty has released a new alpha for his Serpent OS.
-
HashiCorp Cofounder Unveils Ghostty, a Linux Terminal App
Ghostty is a new Linux terminal app that's fast, feature-rich, and offers a platform-native GUI while remaining cross-platform.
-
Fedora Asahi Remix 41 Available for Apple Silicon
If you have an Apple Silicon Mac and you're hoping to install Fedora, you're in luck because the latest release supports the M1 and M2 chips.
-
Systemd Fixes Bug While Facing New Challenger in GNU Shepherd
The systemd developers have fixed a really nasty bug amid the release of the new GNU Shepherd init system.
-
AlmaLinux 10.0 Beta Released
The AlmaLinux OS Foundation has announced the availability of AlmaLinux 10.0 Beta ("Purple Lion") for all supported devices with significant changes.