Python matplotlib Visual Knowledge Point sorting (Summary), pythonmatplotlib
IPython is recommended no matter what project you are working on. Exploitationipython --pylabYou can enter the PyLab mode and have imported the matplotlib library and related software packages (such as Numpy and Scipy). You can directly use the functions of the relevant libraries.
This article is used to sort out some common matplotlib knowledge points during the learning process for easy searching.
In this way, IPython is configured to use the matplotlib GUI backend you specified (TK/wxPython/PyQt/Mac OS X native/GTK ). For most users, the default backend is enough. The Pylab mode also introduces a lot of modules and functions to IPython to provide an interface closer to MATLAB.
import matplotlib.pyplot as pltlabels='frogs','hogs','dogs','logs'sizes=15,20,45,10colors='yellowgreen','gold','lightskyblue','lightcoral'explode=0,0.1,0,0plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=50)plt.axis('equal')plt.show()
The matplotlib icon displays Chinese characters normally.
To display Chinese characters and negative numbers in charts, you need to set the following parameters:
Import matplotlib. pyplot as pltplt. rcParams ['font. sas-serig '] = ['simhei'] # displays the Chinese tag plt normally. rcParams ['axes. unicode_minus '] = False # used to display a negative number normally
Matplotlib inline and pylab inline
Availableipython --pylabOpen the ipython naming window.
% Matplotlib inline # In notebook mode % pylab inline # In ipython Mode
These two commands can embed images in the interactive window rather than a pop-up image window during drawing. However, there is a defect that the drawing cannot be superimposed unless the code is executed once, because in these two modespltThe image will appear immediatelyshowSo:
It is recommended to use ipython notebook, so that you can easily edit the code and draw.
Set the matplotlib parameter for the project
There are two ways to change parameters during code execution:
- Use the parameter Dictionary (rcParams)
- Call the matplotlib. rc () command to modify the parameters by passing in the metadata of the keyword.
If you do not want to configure matplotlib in the Code section every time you use matplotlib, you can modify the file parameters of matplotlib. Availablematplot.get_config()Command to find the current user's configuration file directory.
The configuration file includes the following configuration items:
Axex: sets the color of the coordinate axis boundary and surface, the size of the coordinate scale value, and the display of the grid.
Backend: Set the TkAgg and GTKAgg of the target Summer Promotion.
Figure: Control dpi, border color, image size, and subplot settings
Font: font family, font size, and style settings
Grid: Set grid color and linearity
Legend: Set the legend and text display.
Line: Set the line (color, line type, width, etc.) and flag
Patch: A graphical object that fills a 2D space, such as a polygon or a circle. Controls the width, color, and anti-aliasing settings.
Savefig: You can separately set the saved image. For example, set the background of the rendered file to white.
Verbose: sets matplotlib to output information during execution, such as silent, helpful, debug, and debug-annoying.
Xticks and yticks: Set the color, size, direction, and label size for the main scale and secondary scale of x and Y axis.
Set line-related property tags
Used for the line attributes of the table
| Linestyle or ls |
Description |
Linestyle or ls |
Description |
| '-' |
Solid line |
':' |
Dotted Line |
| '-' |
Broken Line |
'None ','','' |
No painting |
| '-.' |
Dashes |
|
|
Line Mark
| Mark maker |
Description |
Mark |
Description |
| 'O' |
Circle |
'.' |
Point |
| 'D' |
Diamond |
'S' |
Square |
| 'H' |
Hexagonal 1 |
'*' |
Asterisk |
| 'H' |
Hexagonal 2 |
'D' |
Diamond |
| '_' |
Horizontal line |
'V' |
Triangle with one corner down |
| '8' |
Octagonal |
'<' |
Triangle on the left |
| 'P' |
Pentagon |
'>' |
Triangle in the right corner |
| ',' |
Pixels |
'^' |
Triangle with a corner facing up |
| '+' |
Plus sign |
'\ |
' |
Vertical bars |
| 'None ','','' |
None |
'X' |
X |
Color
You can callmatplotlib.pyplot.colors()Obtain all colors supported by matplotlib.
| Alias |
Color |
Alias |
Color |
| B |
Blue |
G |
Green |
| R |
Red |
Y |
Yellow |
| C |
Cyan |
K |
Black |
| M |
Magenta |
W |
White |
If the two colors are not enough, you can define the color values in two ways:
- Use an HTML hexadecimal string
color='eeefff'Use valid HTML color names ('red', 'chartreuse', etc ).
- You can also input an RGB ancestor that is normalized to [0, 1.
color=(0.3,0.3,0.4)
Many methods can introduce color parameters, such as title ().
plt.tilte('Title in a custom color',color='#123456')
Background Color
Forwardmatplotlib.pyplot.axes()Ormatplotlib.pyplot.subplot()This method providesaxisbgParameter, you can specify the background color of the coordinates.
subplot(111,axisbg=(0.1843,0.3098,0.3098)
Basic
If you provide a one-dimensional array or list to the plot () command, matplotlib will default it to a series of y values and automatically generate x values for you. The default x vector starts from 0 and has the same length as y. Therefore, the data of x is [, 2, 3].
Determine the coordinate range plt. axis ([xmin, xmax, ymin, ymax])
The axis () command in the preceding example gives the coordinate range.
Xlim (xmin, xmax) and ylim (ymin, ymax) to adjust the range of x and y coordinates.
% Matplotlib inlineimport numpy as npimport matplotlib. pyplot as pltfrom pylab import * x = np. arange (-5.0, 5.0, 0.02) y1 = np. sin (x) plt. figure (1) plt. subplot (211) plt. plot (x, y1) plt. subplot (212) # Set the X axis range xlim (-2.5, 2.5) # Set the Y axis range ylim (-1, 1) plt. plot (x, y1)
Stacked Graph
Draw lines of different formats with one command.
import numpy as npimport matplotlib.pyplot as plt# evenly sampled time at 200ms intervalst = np.arange(0., 5., 0.2)# red dashes, blue squares and green trianglesplt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')plt.show()
Plt. figure ()
You can use the figure command multiple times to generate multiple images. The image numbers are added in order. Here, pay attention to a concept current graph and the current coordinate. All plotting operations are only valid for the current graph and the current coordinate. Generally, you do not need to consider these things. The following example shows the details.
Import matplotlib. pyplot as pltplt. figure (1) # The first graph plt. subplot (211) # The first subgraph plt in the first graph. plot ([1, 2, 3]) plt. subplot (212) # The second subgraph plt in the first graph. plot ([4, 5, 6]) plt. figure (2) # The second graph plt. plot ([111, 6]) # create subplot () plt by default. figure (1) # Switch to figure 1; subplot (212) of the subgraph is still the current graph plt. subplot (211) # Make subplot (211) The subplot of the subgraph into the plt of the current graph in figure1. title ('easy as 211, 3') # Add the title of subplot
Figure indicates the image ID, which can be indexed and located later.
Plt. text () Add text description
Text () allows you to add text anywhere in a graph and supports LaTex syntax.
Xlable () and ylable () are used to add labels for the X axis and Y axis.
Title () is used to add a graph question.
Import numpy as npimport matplotlib. pyplot as pltmu, sigma = 100, 15x = mu + sigma * np. random. randn (10000) # histogram n, bins, patches = plt. hist (x, 50, normed = 1, facecolor = 'G', alpha = 0.75) plt. xlabel ('smarts') plt. ylabel ('bability ') # Add the title plt. title ('histogram of IQ ') # Add the text plt. text (60 ,. 025, R' $ \ mu = 100, \ sigma = 15 $ ') plt. axis ([40,160, 0, 0.03]) plt. grid (True) plt. show ()
The first two parameters in text should be the coordinates of the text.
Plt. annotate () text comment
In the process of data visualization, the text in the image is often used to comment on some features in the graph. You can use the annotate () method to easily add such annotations. When using annotate, consider the coordinates of two points: xy (x, y) in the commented place and xytext (x, y) in the inserted text ). [^ 1]
import numpy as npimport matplotlib.pyplot as pltax = plt.subplot(111)t = np.arange(0.0, 5.0, 0.01)s = np.cos(2*np.pi*t)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)plt.show()
Plt. xticks ()/plt. yticks () to set the axis mark
Now I understand what it is for, that is, to manually set the value displayed on the scale of the coordinate axis.
# Import all matplotlib content (nympy can be used by the np name) from pylab import * # create an 8*6 point graph, and set the resolution to 80 figure (figsize = (8, 6), dpi = 80) # create a new 1*1 subgraph, the following figure shows the first (and only) subplot (1st, 1) X = np. linspace (-np. pi, np. pi, 256, endpoint = True) C, S = np. cos (X), np. sin (X) # draws the cosine curve, using a blue, continuous, 1 (pixel) Line plot (X, C, color = "blue", linewidth = 1.0, linestyle = "-") # Draw a sine curve using a green, continuous, 1-pixel line plot (X, S, color = "r ", lw = 4.0, linestyle = "-") plt. axis ([-1.2,-1.2,]) # sets the axis mark xticks ([-np. pi,-np. pi/2, 0, np. pi/2, np. pi], [R' $-\ pi $ ', R' $-\ pi/2 $', R' $0 $ ', r' $ + \ pi/2 $ ', R' $ + \ pi $']) yticks ([-1, 0, + 1], [R' $-1 $ ', R' $0 $', R' $ + 1 $ ']) # show () on the screen ()
When we set a tag, we can set the tag at the same time. Note that LaTeX is used here. [^ 2]
Move spine Coordinate System
ax = gca()ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')ax.xaxis.set_ticks_position('bottom')ax.spines['bottom'].set_position(('data',0))ax.yaxis.set_ticks_position('left')ax.spines['left'].set_position(('data',0))
I really don't understand this place. Sorry, I will talk about it later. It feels like I have moved the coordinate axis.
Plt. legend () add legend
plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")legend(loc='upper left')
Matplotlib. pyplot
Useplt.style.use('ggplot')Command to make ggplot-style images.
# Import necessary packagesimport pandas as pd%matplotlib inlineimport matplotlib.pyplot as pltplt.style.use('ggplot')from sklearn import datasetsfrom sklearn import linear_modelimport numpy as np# Load databoston = datasets.load_boston()yb = boston.target.reshape(-1, 1)Xb = boston['data'][:,5].reshape(-1, 1)# Plot dataplt.scatter(Xb,yb)plt.ylabel('value of house /1000 ($)')plt.xlabel('number of rooms')# Create linear regression objectregr = linear_model.LinearRegression()# Train the model using the training setsregr.fit( Xb, yb)# Plot outputsplt.scatter(Xb, yb, color='black')plt.plot(Xb, regr.predict(Xb), color='blue', linewidth=3)plt.show()
Comment on Special Points
Okay, it's a comment. Let's take a look at multiple examples!
We want to add a comment to the two function curves at 2 π/32 π/3. First, draw a point on the corresponding function image position. Then, draw a vertical line to the horizontal axis and mark it with a dotted line. Finally, write the label.
T = 2 * np. pi/3 # As a line segment perpendicular to the X axis. From the mathematical knowledge, we can see that the two points with the same horizontal coordinates are perpendicular to the straight line of the coordinate axis. These two points are the starting point. Plot ([t, t], [0, np. cos (t)], color = 'blue', linewidth = 2.5, linestyle = "--") scatter ([t,], [np. cos (t),], 50, color = 'blue') annotate (R' $ \ sin (\ frac {2 \ pi} {3 }) =\ frac {\ sqrt {3 }}{ 2} $ ', xy = (t, np. sin (t), xycoords = 'data', xytext = (+ 10, + 30), textcoords = 'offset points', fontsize = 16, arrowprops = dict (arrowstyle = "->", connectionstyle = "arc3, rad =. 2 ") plot ([t, t], [0, np. sin (t)], color = 'red', linewidth = 2.5, linestyle = "--") scatter ([t,], [np. sin (t),], 50, color = 'red') annotate (R' $ \ cos (\ frac {2 \ pi} {3 }) =-\ frac {1} {2} $ ', xy = (t, np. cos (t), xycoords = 'data', xytext = (-90,-50), textcoords = 'offset points', fontsize = 16, arrowprops = dict (arrowstyle = "->", connectionstyle = "arc3, rad =. 2 "))
Plt. subplot ()
plt.subplot(2,3,1)Splits the icon into 2*3 grids. It can also be abbreviatedplt.subplot(231). The first parameter indicates the number of rows, the second parameter indicates the number of columns, and the third parameter indicates the graphic label.
Plt. axes ()
Let's first look at what are Figure and Axes objects. In matplotlib, the entire image is a Figure object. A Figure object can contain one or more Axes objects. Each Axes object is a drawing area with its own coordinate system. The logical relationship is as follows:
Plt. axes-official documentation
- Axes () by itself creates a default full subplot (111) window axis.
- Axes (rect, axisbg = 'W') where rect = [left, bottom, width, height] in normalized (0, 1) units. axisbg is the background color for the axis, default white.
- Axes (h) where h is an axes instance makes h the current axis. An Axes instance is returned.
Rect = [left, bottom, width, height] specifies the rectangular area, which is short for rect rectangle. The values here are in the proportion of the figure size. Therefore, if two axes are to be displayed side by side, so the left of axes [2] is axes [1]. left + axes [1]. width, so that axes [2] will not overlap with axes [1.
Show code:
import matplotlib.pyplot as pltimport numpy as np# create some data to use for the plotdt = 0.001t = np.arange(0.0, 10.0, dt)r = np.exp(-t[:1000]/0.05) # impulse responsex = np.random.randn(len(t))s = np.convolve(x, r)[:len(x)]*dt # colored noise# the main axes is subplot(111) by defaultplt.plot(t, s)plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)])plt.xlabel('time (s)')plt.ylabel('current (nA)')plt.title('Gaussian colored noise')# this is an inset axes over the main axesa = plt.axes([.65, .6, .2, .2], axisbg='y')n, bins, patches = plt.hist(s, 400, normed=1)plt.title('Probability')plt.xticks([])plt.yticks([])# this is another inset axes over the main axesa = plt.axes([0.2, 0.6, .2, .2], axisbg='y')plt.plot(t[:len(r)], r)plt.title('Impulse response')plt.xlim(0, 0.2)plt.xticks([])plt.yticks([])plt.show()
Pyplot. pie Parameter
Matplotlib. pyplot. pie
Colors color
Find out the values of colors in matpltlib. pyplot. plot?
- So-Named colors in matplotlib
- Matplotlib learning to set the line color and shape
for name,hex in matplotlib.colors.cnames.iteritems(): print name,hex
Print the color value and the corresponding RGB value.
plt.axis('equal')Avoid proportional compression to an elliptic
Autopct
How do I use matplotlib autopct?
Autopct enables you to display the percent value using Python string formatting. for example, if autopct = '%. 2f ', then for each pie wedge, the format string is' %. 2f 'and the numerical percent value for that wedge is pct, so the wedge label is set to the string' %. 2f '% pct.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.