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
-
Canonical Releases Ubuntu 24.04
After a brief pause because of the XZ vulnerability, Ubuntu 24.04 is now available for install.
-
Linux Servers Targeted by Akira Ransomware
A group of bad actors who have already extorted $42 million have their sights set on the Linux platform.
-
TUXEDO Computers Unveils Linux Laptop Featuring AMD Ryzen CPU
This latest release is the first laptop to include the new CPU from Ryzen and Linux preinstalled.
-
XZ Gets the All-Clear
The back door xz vulnerability has been officially reverted for Fedora 40 and versions 38 and 39 were never affected.
-
Canonical Collaborates with Qualcomm on New Venture
This new joint effort is geared toward bringing Ubuntu and Ubuntu Core to Qualcomm-powered devices.
-
Kodi 21.0 Open-Source Entertainment Hub Released
After a year of development, the award-winning Kodi cross-platform, media center software is now available with many new additions and improvements.
-
Linux Usage Increases in Two Key Areas
If market share is your thing, you'll be happy to know that Linux is on the rise in two areas that, if they keep climbing, could have serious meaning for Linux's future.
-
Vulnerability Discovered in xz Libraries
An urgent alert for Fedora 40 has been posted and users should pay attention.
-
Canonical Bumps LTS Support to 12 years
If you're worried that your Ubuntu LTS release won't be supported long enough to last, Canonical has a surprise for you in the form of 12 years of security coverage.
-
Fedora 40 Beta Released Soon
With the official release of Fedora 40 coming in April, it's almost time to download the beta and see what's new.