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 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.
-
New Pentesting Distribution to Compete with Kali Linux
SnoopGod is now available for your testing needs
-
Juno Computers Launches Another Linux Laptop
If you're looking for a powerhouse laptop that runs Ubuntu, the Juno Computers Neptune 17 v6 should be on your radar.
-
ZorinOS 17.1 Released, Includes Improved Windows App Support
If you need or desire to run Windows applications on Linux, there's one distribution intent on making that easier for you and its new release further improves that feature.
-
Linux Market Share Surpasses 4% for the First Time
Look out Windows and macOS, Linux is on the rise and has even topped ChromeOS to become the fourth most widely used OS around the globe.
-
KDE’s Plasma 6 Officially Available
KDE’s Plasma 6.0 "Megarelease" has happened, and it's brimming with new features, polish, and performance.
-
Latest Version of Tails Unleashed
Tails 6.0 is based on Debian 12 and includes GNOME 43.
-
KDE Announces New Slimbook V with Plenty of Power and KDE’s Plasma 6
If you're a fan of KDE Plasma, you'll be thrilled to hear they've announced a new Slimbook with an AMD CPU and the latest version of KDE Plasma desktop.
-
Monthly Sponsorship Includes Early Access to elementary OS 8
If you want to get a glimpse of what's in the pipeline for elementary OS 8, just set up a monthly sponsorship to help fund its continued existence.