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)