Matplotlib is a drawing library for Python. It contains a number of tools that you can use to create all kinds of graphics, including simple scatter plots, sinusoids, and even three-dimensional graphics.
Import matplotlib.pyplot as PLT import numpy as NPCopy the code
Let me draw a simple graph
So let’s just show you how it works by drawing a sinusoidal graph.
First, x is generated in np.linspace mode, which contains an array of 50 elements evenly distributed on the interval [0, 2pi]. And then you get y from np.sin(x).
x = np.linspace(0, 2 * np.pi, 50)
y = np.sin(x)
Copy the code
Once we have the x and y data, we plot it by plt.plot(x, y) and display it by plt.show().
plt.plot(x, y)
plt.show()
Copy the code
To draw more than one figure on a drawing
Sometimes, it may be necessary to draw more than one figure on a drawing. Here we drew (x, y) and (x, y * 2) at the same time.
plt.plot(x, y)
plt.plot(x, y * 2)
plt.show()
Copy the code
After drawing the graphics, we can adjust more styles ourselves, such as colors, dots and lines.
plt.plot(x, y, 'y*-')
plt.plot(x, y * 2, 'm--')
plt.show()
Copy the code
As you can see, when you set the style, you add a string argument, such as ‘y*-‘, where y represents yellow, * * represents the star point, and — represents the dotted line.
Here are some common color representations:
color | representation |
---|---|
blue | b |
green | g |
red | r |
cyan | c |
magenta | m |
yellow | y |
black | k |
white | w |
Common representation of points:
The type of point | representation |
---|---|
point | . |
pixel | . |
round | o |
square | s |
triangle | ^ |
Common representations of lines:
The type of line | representation |
---|---|
A straight line | – |
Dotted line | — |
Point, line | : |
Point line | -. |
More Settings
Matplotlib supports a variety of flexible Settings, and here are some common ones.
- Set up the figure
You can assume that all the figures Matplotlib draws are in the default figure. Of course, you can create your own figure. The advantage is that you can control more parameters, and the most common is to control the size of the figure.
plt.figure(figsize=(6, 3))
plt.plot(x, y)
plt.plot(x, y * 2)
plt.show()
Copy the code
image
- Set the title
Let’s see how to set the title.
plt.plot(x, y)
plt.plot(x, y * 2)
plt.title("sin(x) & 2sin(x)")
plt.show()
Copy the code
The graphic title can be set directly through plt.title.
- Set coordinate axes
Let’s see how to set the range and name of the axes.
plt.plot(x, y)
plt.plot(x, y * 2)
plt.xlim((0, np.pi + 1))
plt.ylim((-3, 3))
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Copy the code
Xlim and ylim are used to set the scope of the qualified axis, and xlabel and ylabel are used to set the name of the axis.
In addition, we can also set the scale of the shaft with xTicks and yticks.
Plt.plot (x, y) plt.plot(x, y * 2) plt.xticks((0, np.pi * 0.5, np.pi, nP.pi * 1.5, nP.pi * 2)) plt.show()Copy the code
- Setting label and Legend The purpose of setting label and legend is to distinguish the graphic name corresponding to each data.
plt.plot(x, y, label="sin(x)")
plt.plot(x, y * 2, label="2sin(x)")
# plt.legend()
plt.legend(loc='best')
plt.show()
Copy the code
- Add comments
Sometimes we need to annotate specific points, which we can do with the plt.annotate function.
The point we want to label here is (x0, y0) = (PI, 0).
We can also use the plt.text function to add comments.
Plt. scatter(x0, y0, s=50) plt.annotate('sin(np.pi)=%s' % y0, xy=(np.pi, 0), xycoords='data', xytext=(+30, -30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle='->', Connectionstyle = "arc3, rad = 2")) PLT. Text (0.5, 0.25, "sin (np) PI) = 0", fontdict = {' size: 16, 'color', 'r'}) PLT. The show ()Copy the code
‘sin(np.pi)=%s’ % y0 represents the annotated content, and the value of y0 can be passed to the string %s. The parameter xycoords=’data’ is used to select the position based on the value of the data; Xytext =(+30, -30) and TextCoords =’offset points’ represent the description of the annotation position and the XY deviation value, that is, the annotation position is moved 30 to the right and 30 to the down; The arrowprops are Settings for the types and radians of the arrows in the figure. You need to pass in the dict format.
- Use the subgraph
Sometimes we need to display multiple subplots together, using subplot(). That is, the subplot() function needs to be called before the plot() function is called. The first argument to this function represents the total number of rows in the subgraph, the second argument represents the total number of columns in the subgraph, and the third argument represents the active region.
Ax1 = plt.subplot(2, 2, 1) # Plot (x, 2 * np.sin(x), 'r') ax2 = plt.subplot(2, 2, 2, sharey=ax1) # 'g') ax3 = plt.subplot(2, 2, 3) plt.plot(x, np.cos(x), 'b') ax4 = plt.subplot(2, 2, 4, Plt.plot (x, 2 * np.cos(x), 'y') plt.show()Copy the code
Subplot (2, 2, x) above means that the image window is divided into 2 rows and 2 columns. X represents the active region of the current subgraph.
As you can see, each of the above subgraphs is of the same size. Sometimes we need subgraphs of different sizes. For example, place the first subgraph above entirely on the first row and all other subgraphs on the second row.
Ax1 = plt.subplot(2, 1, 1) # Plot (x, 2 * np.sin(x), 'g') ax3 = plt.subplot(2, 3, 4) plt.plot(x, 2 * np.sin(x), 'g') ax3 = plt.subplot(2, 3, 5) sharey=ax2) plt.plot(x, np.cos(x), 'b') ax4 = plt.subplot(2, 3, 6, sharey=ax2) plt.plot(x, 2 * np.cos(x), 'y') plt.show()Copy the code
For a brief explanation, plt.subplot(2, 1, 1) divides the image window into 2 rows and 1 column, and the current active area is 1.
Use plt.subplot(2, 3, 4) to divide the entire image window into 2 rows and 3 columns, with the current active area being 4.
Explain why the active area is 4, because plt.subplot(2, 1, 1) was used in the previous step to divide the whole image window into 2 rows and 1 column, and the first small graph occupies the first position, that is, the entire first row. In this step, plt.subplot(2, 3, 4) is used to divide the entire image window into 2 rows and 3 columns, so the first row of the entire image window becomes 3 columns, that is, 3 positions, so the first position of the second row is the fourth position of the entire image window.
Common graphics
Here are some common examples.
- Scatter plot First let’s look at how to draw a scatter plot.
K = 500 x = np.random.rand(k) y = np.random.rand(k) size = Np.random.rand (k) * 50 # Generate each point size colour = np.arctan2(x, Scatter (x, y, s=size, c=colour) plt.colorbar() # add colorbar plt.show()Copy the code
First we generate the data points x and y, then we generate the array size for each data point, and then we generate the array colour for each data point. Finally, add a colorbar with colorbar().
- Bar charts Bar charts are often used, so let’s see how to draw a bar chart and label the values of the data on the chart.
X = np.arange(k) y = np.random.rand(k) plt.bar(x, y) # plt.text(x, y , '%.2f' % y, ha='center', va='bottom') plt.show()Copy the code
After generating data x and y, the plt.bar function is called to draw the bar graph, then the values are labeled with plt.text, with ha=’center’ aligned horizontally and VA =’bottom’ aligned vertically to the bottom (top).
- One annoying problem with Matplotlib is that by default, Matplotlib Chinese is garbled.
X = [' Beijing ', 'Shanghai', 'shenzhen', 'guangzhou] y = [60000, 58000, 50000, 52000] PLT. The plot (x, y) PLT. The show ()Copy the code
It can be seen that all the above Chinese characters are garbled and displayed as a box, how to solve it?
In fact, you only need to configure the background font.
RcParams ['axes. Unicode_minus ']=False # y) plt.show()Copy the code
Welcome to pay attention to the public number: algorithm engineer learning log