How to make a Teddy bear

Date: 11.10.2018, 15:40 / View: 81171

Task: continue to get high-quality graphics without leaving python 🙂
Стру? Tool: Matplotlib

This is a continuation of the previous post. Today we will look at how to display two graphs in one window, how to do this in different windows, how to add mathematical expressions to axes labels and anywhere in the graph, as well as how to sign some detail on the graph that you especially like.
Working with multiple windows and axes in Matplotlib

? matlab and pyplot use the concept of an active window and active axes. All drawing commands of anything apply to exactly the active axes. The gca () function returns the active axes (an instance of the matplotlib.axes.Axes class), and gcf () returns the active window (figure) (an instance of the matplotlib.figure.Figure class). Below is a script to create two graphs on one image:

import numpy as np
import matplotlib.pyplot as plt
def f (t):
return np.exp (-t) np.cos (2np.pit)
t1 = np.arange (0.0, 5.0, 0.1)
t2 = np.arange (0.0, 5.0, 0.02)
plt.figure (1)
plt.subplot (211)
plt.plot (t1, f (t1), 'bo', t2, f (t2), 'k')
plt.subplot (212)
plt.plot (t2, np.cos (2np.pit2), 'r--') ()


The figure () command is not necessary here, since figure (1) will be created by default, as well as the sub-window (yes, such a beautiful word 🙂) subplot (111) will be created by default, if you have not manually defined the axes. The subplot () command determines how many subwindows your window will be broken into, and which of them will output your output. In this case, it takes as the arguments the number of rows (numrows), the number of columns (numcols) and the number of the subwindow (fignum), which varies from 1 to numrowsnumcols (subplot (numrows, numcols, fignum)). If numrowsnumcols <10, then commas are not necessary to put, that is, subplot (211) and subplot (2,1,1) are identical to each other. You can create as many windows as you need and axles. If you want to position the axes (subwindows) manually, for example, not on a rectangular grid, but somehow like a Christmas tree, use the axes () command, which allows you to define the position of the axes as axes ([left, bottom, width, height]), where all the values change from 0 to 1. It can look like this:

import numpy as np
import matplotlib.pyplot as plt
def f (t):
return np.exp (-t) np.cos (2np.pit)
t1 = np.arange (0.0, 5.0, 0.1)
t2 = np.arange (0.0, 5.0, 0.02)
plt.figure (1)
plt.axes ([0.55, 0.55, 0.4, 0.4])
plt.plot (t1, f (t1), 'bo', t2, f (t2), 'k')
plt.axes ([0.3, 0.3, 0.4, 0.4])
plt.plot (t2, np.cos (2np.pit2), 'r--')
plt.axes ([0.05, 0.05, 0.4, 0.4])
plt.plot (t1, f (t1), 'bo', t2, f (t2), 'k') ()


You can create multiple windows by calling figure () with an increasing window number. Of course, each window can contain as many axes and a subwindow as your heart desires.

import matplotlib.pyplot as plt
plt.figure (1) # the first figure
plt.subplot (211) # the first subplot in the first figure
plt.plot ([1,2,3])
plt.subplot (212) # the second subplot in the first figure
plt.plot ([4,5,6])
plt.figure (2) # a second figure
plt.plot ([4,5,6]) # creates a subplot (111) by default
plt.figure (1) # figure 1 current; subplot (212) still current
plt.subplot (211) # make subplot (211) in figure1 current
plt.title ('Easy as 1,2,3') # subplot 211 title ()

Will create two windows:

You can clear the active window with clf (), and the active axes with cla (). Working with text in matplotlib

The text () command can be used to add text in an arbitrary location (by default, the coordinates are specified in the coordinates of the active axes), and the xlabel (), ylabel () and title () commands are used to sign the x-axis, the y-axis and the entire graph, respectively. For more information, see the Text introduction section on ofsayte.

import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma np.random.randn (10,000)
# the histogram of the data
n, bins, patches = plt.hist (x, 50, normed = 1, facecolor = 'g', alpha = 0.75)
plt.xlabel ('Smarts')
plt.ylabel ('Probability')
plt.title ('Histogram of IQ')
plt.text (60, .025, r '$ \ mu = 100, \ \ sigma = 15 $')
plt.axis ([40, 160, 0, 0.03])
plt.grid (True) ()


All text () commands return an instance of matplotlib.text.Text. Just as with lines, you can change text properties by passing keywords to text functions or using setp ().

So, to make a signature on the x-axis red and 14m font size, you need to write:

t = plt.xlabel ('my data', fontsize = 14, color = 'red')

This is described in more detail in Text properties and layout. ? use of mathematical expressions in the text

Matplotlib understands formulas written in the syntax of TeX and can insert them into any text. For example, in order to write a mathematical expression in the header, you need to surround the string in the TeX format with dollar signs:

plt.title (r '$ \ sigma_i = 15 $')

The character r before the line is important, it means that the next is a clean line and you do not need to handle the backslash and escape characters (more on this here). Matplotlib has its own built-in TeX expressions parser and output engine, it also provides its own math fonts (for more details, Writing mathematical expressions). This way you can use mathematical expressions on any platform without having to install TeX. How to cross matplotlib with LaTeX can be found in the section Text rendering With LaTeX.

If we add these pair of lines to the previous example with the histogram:

plt.text (60, .030, r '$ \ mu = 100, \ \ sigma = 15 $')
plt.text (50, .033, r '$ \ varphi _ {\ mu, \ sigma ^ 2} (x) = \ frac {1} {\ sigma \ sqrt {2 \ pi}} \, e ^ {- \ frac {(x- \ mu) ^ 2} {2 \ sigma ^ 2}} = \ frac {1} {\ sigma} \ varphi \ left (\ frac {x - \ mu} {\ sigma} \ right), \ quad x \ in \ mathbb {R} $ ', fontsize = 20, color =' red ')

then we get such a beauty:
pyplot206.png Text Signatures

? Using the text () command, discussed above, puts the text in an arbitrary place in the graph. Often, text is used to sign some detail on a chart, and the annotate () method provides supporting functionality to make such signing easier. The two main things you need to provide this method are the position of the point you will be signing (x y coordinates) and the position of the text of the signature. Miraculously, an arrow will be drawn between these positions, the properties of which you can also control.

import numpy as np
import matplotlib.pyplot as plt
ax = plt.subplot (111)
t = np.arange (0.0, 5.0, 0.01)
s = np.cos (2np.pit)
line, = plt.plot (t, s, lw = 2)
plt.annotate ('local max', xy = (2, 1), xytext = (3, 1.5),
arrowprops = dict (facecolor = 'black', shrink = 0.05),
plt.ylim (-2,2) ()


In this simple example, the positions of xy (where the arrow is pointing), and xytext (the signature itself) are specified in data coordinates (active axes). You can choose other coordinate systems, details in Annotating text

Related news:

Chain with your hands

ReCache | DelPage
Memory used: 44.84KB of 768KB
Render time: 0.022 sec