Matplotlib basis

Python classic drawing library for processing data drawing

Matplotlib can output graphics using a variety of back-end graphics libraries (Tk, wxPython, etc.). When you run Python from the command line, the graphics are usually displayed in a separate window.

Import dependencies:

import matplotlib

In Jupyter, you can simply output graphics in a notebook by running the %matplotlib inline magic command.

%matplotlib inline
# matplotlib.use("TKAgg") # use this instead in your program if you want to use Tk as your graphics backend.
Copy the code

Base drawing X-Y

The plot () and show ()

The plot function plots the data, and the show function displays it

If you give the “plot” function an array, it uses that array as the coordinate on the vertical axis and the index of each data point in the array as the horizontal axis.

import matplotlib.pyplot as plt
plt.plot([1.2.4.9.5.3])
plt.show()
Copy the code

You can also provide two arrays: one for the horizontal axis “x” and one for the vertical axis “y” :

plt.plot([-3, -2.5.0], [1.6.4.3])
plt.show()
Copy the code

Scoping Axis ()

The axis function is used to define the range of x and y axes

The X-axis and Y-axis automatically match the range of data. Limiting the boundary range requires calling the ‘axis’ function to change the range of each axis

The array [xmin, xmax, ymin, ymax] is passed.

plt.plot([-3, -2.5.0], [1.6.4.3])
plt.axis([-4.6.0.7])
plt.show()
Copy the code

Draw a mathematical function

Numpy linspace ()

Basic drawing draws point coordinate system (x,y)(x,y)(x, Y). Mathematical functions such as curve drawing need to use NUMPY library to generate continuous multiple data points and transfer them to plot for drawing

import numpy as np
x = np.linspace(-2.2.500)
y = x**2

plt.plot(x, y)
plt.show()
Copy the code

Let’s draw a mathematical function that uses NumPy’s linspace function to create an array ‘x’ that contains 500 floating point numbers from -2 to 2, and then creates a second array ‘y’ that evaluates to the square of ‘x’

Add titles and labels

Title (), xlabel(), ylabel() and grid()

  • Title () is used to add the graph name
  • Xlabel () and ylabel() are used to prompt for x – and Y-axis labels
  • Grid () is used to set whether the background is drawn in a table
plt.plot(x, y)
plt.title("Square function")
plt.xlabel("x")
plt.ylabel("y = x**2")
plt.grid(True)
plt.show()
Copy the code

style

Default drawing mode

By default, the matplotlib for a given (x, y) (x, y) (x, y) are connected by drawing, namely data points [a, b, c, a] will be in accordance with the a – > b – > c – aa – > – > b > c – > aa – – > b > c – > a way to draw in a row

plt.plot([0.100.100.0.0.100.50.0.100], [0.0.100.100.0.100.130.100.0])
plt.axis([-10.110, -10.140])
plt.show()
Copy the code

Third argument to plot()

When drawing, you can pass a third parameter to change the style and color of the line. X1, y1, [style1], x2, y2, [style2],… This specifies the style of the data points group

For example, “G –” stands for “green dotted line.” R represents red and – represents solid lines

plt.plot([0.100.100.0.0], [0.0.100.100.0]."r-"[0.100.50.0.100], [0.100.130.100.0]."g--")
plt.axis([-10.110, -10.140])
plt.show()
Copy the code

Alternatively, call plot multiple times before show (load data, set styles)

plt.plot([0.100.100.0.0], [0.0.100.100.0]."r-")
plt.plot([0.100.50.0.100], [0.100.130.100.0]."g--")
plt.axis([-10.110, -10.140])
plt.show()
Copy the code

Draw only points, not lines

It is also possible to draw simple points instead of lines. Here is an example with a green dotted line, a red dotted line, and a blue triangle. See the Matplotlib documentation for a complete list of style and color options.

x = np.linspace(-1.4.1.4.30)
plt.plot(x, x, 'g--', x, x**2.'r:', x, x**3.'b^')#blue ^ stands for triangle
plt.show()
Copy the code

The return value of plot()

Set the style

The plot function returns a list of “Line2D” objects (one per line). You can set additional properties on these lines, such as line width, dashed line style, or alpha level. Reference documentation: Line style

x = np.linspace(-1.4.1.4.30)
line1, line2, line3 = plt.plot(x, x, 'g--', x, x**2.'r:', x, x**3.'b^')
line1.set_linewidth(3.0)
line1.set_dash_capstyle("round")
line3.set_alpha(0.2)
plt.show()
Copy the code

Save the picture

savefig()

The savefig() function is used to save images

x = np.linspace(-1.4.1.4.30)
plt.plot(x, x**2)
plt.savefig("my_square_function.png", transparent=True)
Copy the code

Plot multiple plots

subplot()

Matplotlib diagrams may contain multiple subgraphs. These subplots are organized in a grid. To create a subplot, simply call the subplot function and specify the number of rows and columns in the plot, as well as the index of the subplot to be plotted (starting at 1, then left to right and top to bottom).

plt.subplot(2, 2, 1) I can write it as thetaplt.subplot(221)

x = np.linspace(-1.4.1.4.30)
plt.subplot(2.2.1)  # 2 rows, 2 columns, 1st subplot = top left
plt.plot(x, x)
plt.subplot(2.2.2)  # 2 rows, 2 columns, 2nd subplot = top right
plt.plot(x, x**2)
plt.subplot(2.2.3)  # 2 rows, 2 columns, 3rd subplot = bottow left
plt.plot(x, x**3)
plt.subplot(2.2.4)  # 2 rows, 2 columns, 4th subplot = bottom right
plt.plot(x, x**4)
plt.show()
Copy the code

Note the concept of rows and columns, where rows and columns are used for segmentation

plt.subplot(2.2.1)  # 2 rows, 2 columns, 1st subplot = top left
plt.plot(x, x)
plt.subplot(2.2.2)  # 2 rows, 2 columns, 2nd subplot = top right
plt.plot(x, x**2)
plt.subplot(2.1.2)  # 2 rows, *1* column, 2nd subplot = bottom
plt.plot(x, x**3)
plt.show()
Copy the code

Instead of occupying a fixed size column, the top column occupies a whole column of the diagram

subplot2grid()

If more complex subplot positioning is required, use subplot2Grid instead of subplot. Specify the number of rows and columns in the grid, and then specify the position of the subblock in that grid (upper left = (0,0)), and optionally the number of rows and/or columns that the subblock spans. Such as:

#3row 3col, starting at 00, occupies 2row 2col
plt.subplot2grid((3.3), (0.0), rowspan=2, colspan=2)
plt.plot(x, x**2)
plt.subplot2grid((3.3), (0.2))
plt.plot(x, x**3)
plt.subplot2grid((3.3), (1.2), rowspan=2)
plt.plot(x, x**4)
plt.subplot2grid((3.3), (2.0), colspan=2)
plt.plot(x, x**5)
plt.show()
Copy the code

figure()

Multiple plots can be specified. Each diagram may contain one or more subgraphs. By default, Matplotlib automatically creates Figure 1. You can switch at any time

x = np.linspace(-1.4.1.4.30)

plt.figure(1)
plt.subplot(211) / /2 row 1 col
plt.plot(x, x**2)
plt.title("Square and Cube")
plt.subplot(212)
plt.plot(x, x**3)

plt.figure(2, figsize=(10.5))
plt.subplot(121) / /1 row 2 col
plt.plot(x, x**4)
plt.title("y = x**4")
plt.subplot(122)
plt.plot(x, x**5)
plt.title("y = x**5")

plt.figure(1)      # back to figure 1, current subplot is 212 (bottom)
plt.plot(x, -x**3."r:")

plt.show()
Copy the code

The return value of the subplots()

Calling the subplots() implicitly creates a plot and subplots, returns one plot object and multiple subplots(depending on the argument, for example, two rows and one column of the subplots(2,1) return the upper and lower plots), and plots the plots according to the returned subplots

x = np.linspace(-2.2.200)
fig1, (ax_top, ax_bottom) = plt.subplots(2.1, sharex=True)
fig1.set_size_inches(10.5)
line1, line2 = ax_top.plot(x, np.sin(3*x**2), "r-", x, np.cos(5*x**2), "b-")
line3, = ax_bottom.plot(x, np.sin(3*x), "r-")
ax_top.grid(True)

fig2, ax = plt.subplots(1.1)
ax.plot(x, x**2)
plt.show()
Copy the code

Draw text

text()

Text () is used to draw text anywhere in the graph and set properties. You only need to specify horizontal and vertical coordinates and text, and optionally specify some additional properties. Any text in matplotlib can contain TeX equation expressions, see documentation

x = np.linspace(-1.5.1.5.30)
px = 0.8
py = px**2

plt.plot(x, x**2."b-", px, py, "ro")

plt.text(0.1.5."Square function\n$y = x^2$", fontsize=20, color='blue', horizontalalignment="center") //ha is the horizontalalignment abbreviation plt.text(px -0.08, py, "Beautiful point", ha="right", weight="heavy")
plt.text(px, py, "x = %0.2f\ny = %0.2f"%(px, py), rotation=50, color='gray')

plt.show()
Copy the code

Annotate ()

It is very common to comment on graphic elements, such as the beauty points above. The Annotate function makes this easy: simply indicate the position of the point of interest and the position of the text, with the option to add some additional attributes to the text and arrows.

plt.plot(x, x**2, px, py, "ro")
plt.annotate("Beautiful point", xy=(px, py), xytext=(px-1.3,py+0.5),
                           color="green", weight="heavy", fontsize=14,
                           arrowprops={"facecolor": "lightgreen"})
plt.show()
Copy the code

Legend legend ()

This can be used with the parameter label in plot() to describe the legend in the graph. The location of the legend can be specified by the keyword parameter LOc (location).

x = np.linspace(-1.4.1.4.50)
plt.plot(x, x**2."r--", label="Square function")
plt.plot(x, x**3."g-", label="Cube function")
plt.legend(loc="best")
plt.grid(True)
plt.show()
Copy the code

Nonlinear ratio

yscale()

Supports nonlinear scales for x – and Y-axis scales, such as exponential and logarithmic scales

x = np.linspace(0.1.15.500)
y = x**3/np.exp(2*x)

plt.figure(1)
plt.plot(x, y)
plt.yscale('linear') / / linear PLT. Title ('linear')
plt.grid(True)

plt.figure(2)
plt.plot(x, y)
plt.yscale('log') / / index PLT. Title ('log')
plt.grid(True)

plt.figure(3)
plt.plot(x, y)
plt.yscale('logit') / / logarithmic PLT. Title ('logit')
plt.grid(True)

plt.figure(4)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.05)
plt.title('symlog')
plt.grid(True)

plt.show()
Copy the code

Control x axis and y axis calibration

The return object plotted by plot() has two attributes, xaxis and yaxis, through which scale ranges can be specified

x = np.linspace(-2.2.100)

plt.figure(1, figsize=(15.10))
plt.subplot(131)
plt.plot(x, x**3)
plt.grid(True)
plt.title("Default ticks")

ax = plt.subplot(132)
plt.plot(x, x**3)
ax.xaxis.set_ticks(np.arange(-2.2.1))
plt.grid(True)
plt.title("Manual ticks on the x-axis")

ax = plt.subplot(133)
plt.plot(x, x**3)
plt.minorticks_on()
ax.tick_params(axis='x', which='minor', bottom=False)
ax.xaxis.set_ticks([-2.0.1.2])
ax.yaxis.set_ticks(np.arange(-5.5.1))
ax.yaxis.set_ticklabels(["min", -4, -3, -2, -1.0.1.2.3."max"])
plt.title("Manual ticks and tick labels\n(plus minor ticks) on the y-axis")


plt.grid(True)

plt.show()
Copy the code

A scatter diagram

scatter()

Pass x array and Y array parameters and scatter() draws scatter graph

from numpy.random import rand
x, y = rand(2.100)
plt.scatter(x, y)
plt.show()
Copy the code

Specifies the scatter size

Specify the S (scale) array in Scatter () to specify the scatter size

x, y, scale = rand(3.100)
scale = 500 * scale ** 5
plt.scatter(x, y, s=scale)
plt.show()
Copy the code

histogram

hist()

Frequency histogram, the simplest given the original data set to plot the frequency histogram

data = [1.1.1.1.8.2.2.1.3.2.3.3.3.3]
plt.subplot(211)
plt.hist(data, bins = 10, rwidth=0.8Plt. subplot()212)
plt.hist(data, bins = [1.1.5.2.2.5.3], rwidth=0.95)
plt.xlabel("Value")
plt.ylabel("Frequency")

plt.show()
Copy the code

The bins parameter specifies the number of intervals in the histogram, passing values directly to indicate how many partitions are to be divided according to the number of elements in data

Common attributes are:

  • Color, specifies the fill color for the column
  • Edgecolor, specifies the color of the column border
  • Density: specifies the information corresponding to the column height. There are two options: numerical value and frequency
  • Orientation: Specifies the orientation of the column, both horizontal and vertical
  • Histtype, the type of drawing
data1 = np.random.randn(400)
data2 = np.random.randn(500) + 3
data3 = np.random.randn(450) + 6
data4a = np.random.randn(200) + 9
data4b = np.random.randn(100) + 10

plt.hist(data1, bins=5, color='g', alpha=0.75, label='bar hist') # default histtype='bar'
plt.hist(data2, color='b', alpha=0.65, histtype='stepfilled', label='stepfilled hist')
plt.hist(data3, color='r', histtype='step', label='step hist')
plt.hist((data4a, data4b), color=('r'.'m'), alpha=0.55, histtype='barstacked', label=('barstacked a'.'barstacked b'))

plt.xlabel("Value")
plt.ylabel("Frequency")
plt.legend()
plt.grid(True)
plt.show()
Copy the code

Read the pictures

Imread with imshow () ()

Reading, generating, and printing images in Matplotlib is simple.

To read the image, simply import the matplotlib.image module and call its imread function, passing it the filename (or file object). This returns image data as a NumPy array.

import matplotlib.image as mpimg

img = mpimg.imread('my_square_function.png')
print(img.shape, img.dtype)
Copy the code

We have loaded a 288×432 image. Each pixel is represented by a 4-element array: red, green, blue, and alpha levels, stored as 32-bit floating-point values between 0 and 1. The numpy array is returned, which can be drawn by calling imshow()

plt.imshow(img)
plt.show()
Copy the code

Calling Axis () hides the axis that was added automatically

plt.imshow(img)
plt.axis('off')
plt.show()
Copy the code

The imshow function will automatically map the value to the color gradient. By default the color gradient changes from blue (low value) to red (high value)

img = np.arange(100*100).reshape(100.100)
print(img)
plt.imshow(img)
plt.show()
Copy the code

3 d projection

Drawing 3d graphics is very simple. You need to import Axes3D, which registers a 3D projection. Then create a subplot, set “Projection” to “3D” and return an “Axes3DSubplot” object that you can use to call plot_surface to give x, Y, and Z coordinates and optional properties.

from mpl_toolkits.mplot3d import Axes3D

x = np.linspace(-5.5.50)
y = np.linspace(-5.5.50)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

figure = plt.figure(1, figsize = (12.4))
subplot3d = plt.subplot(111, projection='3d')
surface = subplot3d.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=matplotlib.cm.coolwarm, linewidth=0.1)
plt.show()
Copy the code

It is also possible to simply draw a projection through Contourf

plt.contourf(X, Y, Z, cmap=matplotlib.cm.coolwarm)
plt.colorbar()
plt.show()
Copy the code

Content sources

  1. Practical guide to Sklearn and TensorFlow machine Learning 2nd edition
  2. Github.com/ageron/hand…