Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.
preface
In this series of posts, we’ve learned how to customize the colors and styles of your drawings to make them more elegant and aesthetically pleasing. It is possible to use Matplotlib to draw complex and elegant graphs, but without annotations, it is difficult for others to understand what the dots and lines in the graph mean, and thus lose the meaning of the graph. To solve this problem, Matplotlib provides a number of ways to annotate graphs. These annotation methods are common to all plotting functions (such as plt.plot(), plt.scatter(), plt.histogram(), etc.) and can be used to make statistical graphs easy to understand.
Add the title
Start with the simplest way to add a title:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-4.4.10005)
y = 5 * (x + 4.2) * (x + 4.) * (x - 2.5)
plt.title('A polynomial')
plt.plot(x, y, c = 'm')
plt.show()
Copy the code
The Tips: plt.title() function takes a string as an argument and uses it as the title of the entire graph.
Label the axes
In practical application, the proper description of the coordinate axes of a statistical graph helps users to understand the meaning of the graph.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.8.1000)
y = 2.0 * x + 0.5 * 5 * x ** 2
plt.title('Acceleration Moving')
plt.xlabel('Time')
plt.ylabel('distance')
plt.plot(x, y, c = 'c')
plt.show()
Copy the code
Tips: Annotate the horizontal and vertical axes using the plt.xlabel() and plt.ylabel() functions, respectively.
Add the arrow
Adding text boxes can certainly help annotate graphics, but sometimes there’s too much explanatory text to make it clear what part of the graph corresponds to, so there’s no better way to annotate a particular part of the graph than with arrows, which Matplotlib draws using the plt.annotate() function.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.8.1000)
y = 2.0 * x + 0.5 * 5 * x ** 2
plt.annotate('start',
ha = 'center', va = 'bottom',
xytext = (2.30.),
xy = (0.0),
arrowprops = { 'facecolor' : 'black'.'shrink' : 0.05 })
plt.title('Acceleration Moving')
plt.plot(x, y, c = 'c')
plt.show()
Copy the code
The Tips: plt.annotate() function renders arrows in addition to the annotated text that does the same thing as plt.text(). The description text to display is the first argument; The xy argument specifies the target of the arrow; The xytext argument specifies the position of the text. You can also change the alignment of the text with the HA and VA arguments
The style of the arrow is controlled by the dictionary passed to the arrowprops parameter, where the commonly used keys include:
key | Description and optional values |
---|---|
arrowstyle | Controls the style of the arrow. Options include “<-“, “<“, “wedge”, “simple”, and “fancy” |
facecolor | Used to set the color of the arrow background and edge |
edgecolor | Used to set the color of the arrow edges |
alpha | Used to set the opacity level to better blend the arrows with the background |
The shrink parameter controls the gap between the end of the arrow and the arrow itself.
Add a legend
Complex graphs often contain a large number of different curves and points. If these curves and points do not have corresponding legends, they cannot be accurately distinguished. Therefore, legends are essential in practice. The plt.legend() function and the label of the drawing function are optional arguments to add legends:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.6.1024)
data = np.random.standard_normal((150.2))
print(data.size)
y_1 = np.sin(x)
y_2 = np.cos(x)
plt.xlabel('x')
plt.ylabel('y')
plt.plot(x, y_1, c = 'm', lw = 3., label = 'sin(x)')
plt.plot(x, y_2, c = 'c', lw = 3., ls = The '-', label = 'cos(x)')
plt.scatter(data[:,0],data[:,1],c='y', label = 'random')
plt.legend()
plt.show()
Copy the code
Tips: Each PLT plotting function (plt.plot(), plt.scatter(), etc.) has an optional label parameter to name the elements of the graph. The plt.legend() function renders the legend, which is automatically generated from the label. The plt.legend() function contains optional arguments to control the rendering of the legend:
parameter | Description and optional values |
---|---|
loc | Used to control the position of the legend, default is “best”, will automatically place the legend in the appropriate way, Other optional values include “upper left”, “lower left”, “lower right”, “right”, “center left”, “center right”, “lower Center “, and “upper” Center “and” center” |
shadow | Optional values, including True and False, set whether to render legends with a shadow effect |
fancybox | Optional values include True and False for whether to render legends with rounded boxes |
title | Use to set the title for the legend |
ncol | Forces the number of columns for the legend |
Use LaTex style symbols
We’ve learned how to add multiple annotations to a graph. In practice, however, we usually need to use mathematical symbols, so we need to use LaTex syntax to add numeric symbols. To use LaTex style symbols, you first need to install the available LaTex configuration on your computer so that Matplotlib can interpret LaTex syntax to render mathematical text. There is a method for installing LaTeX that is not in the subject of this article, and you can retrieve the installation method based on your operating system.
Introduction of LaTex
LaTex is a document typesetting system widely used in academia. Unlike document editors such as Microsoft Word, LaTeX users cannot see the final display of a document when they edit it. Documents are described as text and commands stored in plain text documents. Finally, LaTeX will interpret the document for rendering. In the scientific and engineering world, LaTeX’s formula language is commonly used for writing mathematical text in emails and forums.
Use a LaTex symbol example
When using LaTex style symbols, functions accept string parameter values that start and end with the “$” character, which signals to Matplotlib to interpret and render the text as LaTex style mathematical text. The contents of strings are the standard language for mathematical text. For an introduction to LaTeX style mathematical text in Matplotlib, see the Matplotlib website.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-4.4.10005)
y = 3 / 5 * (x + 4.2) * (x + 4.) * (x - 2.5)
plt.title('$f (x) = \ \ frac {3} {5} (x + 4) (x + 4.4) (2.5) x $')
plt.plot(x, y, c = 'k')
plt.show()
Copy the code
Tips: This LaTex style notation is not limited to headings; it can be used for any other comment. The LaTeX language relies heavily on the escape character \, but this symbol also happens to be Python's string escape character. Therefore, if you want to use \ as a transfer character in a LaTeX text, you need to use two \ in Python strings. In order to avoid miss escape character, can add a r in front of the string, so it does not require any escape character, that is: "$f (x) = \ \ frac {1} {4} (x + 4) (x + 1) (2) x - $" is equivalent to r '$f (x) = \ frac {1} {4} (x + 1) (x + 4) $' (x - 2).
Use Chinese characters
Chinese is a pain point in using Matplotlib, but in practical application, it is inevitable to use Chinese to display statistical graph annotation. If not configured, Chinese characters will be displayed as garbled characters. There are several ways to use Chinese characters as annotations, here we use plt.rcparams [‘font. Sans-serif ‘] in the philosophy that simplicity is best:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.6.1024)
data = np.random.standard_normal((150.2))
y_1 = np.sin(x)
y_2 = np.cos(x)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Examples of Chinese Characters')
plt.plot(x, y_1, c = 'm', lw = 3., label = Sine function)
plt.plot(x, y_2, c = 'c', lw = 3., ls = The '-', label = Cosine function)
plt.scatter(data[:,0],data[:,1],c='y', label = 'Random point')
plt.rcParams['font.sans-serif'] = ['SimSun']
plt.legend()
plt.show()
Copy the code
Tips: Use plt.rcparams ['font. Sans-serif '] to set the font to support Chinese characters. The use of Chinese characters is the same as that of LaTex style symbols.
Series of links
Matplotlib common statistical graph drawing
Matplotlib uses custom colors to draw statistics
Matplotlib controls line style and line width
Matplotlib custom style to draw beautiful statistics
Matplotlib adds text instructions to the graph