Introduction and practice of matplotlib

I have always encountered which function Baidu and which function in matplotlib. It is a bit annoying if there are too many times, so I simply make a knowledge list and learn it systematically.

1. Quick Drawing

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 1000)# returns 1000 points evenly at (0,10)
y = np.sin(x)
z = e.g. cos (x ** 2)

plt.figure(figsize=(8,4)) #Set the size to 800*400 pixels
plt.plot(x,y,label="sin(x)",color="red",linewidth=2)
plt.plot(x,z,"b--",label="cos(x^2)")
plt.xlabel("Time(s)")
plt.ylabel("Volt")
plt.title("PyPlot First Example")
plt.ylim(-1.2,1.2) #y drawing range
plt.legend() #Display the legend, that is, display the label
plt.show()

There is a line type parameter in plot()

linesyle: '-' solid line, '--' short line, '-.' short dotted line, ':' dotted line.



2. Draw a multi-axis graph

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

plt.subplot(221) # Left image of the first line
plt.subplot(222) # The right image of the first line
plt.subplot(212) # Second whole line
plt.show()

subplot(numRows, numCols, plotNum)

subplot divides the entire plot area into numRows row * numCols column sub-areas, and then numbers each sub-area in the order from left to right, top to bottom, and the number of the upper left sub-area is 1. Choose to plot at plotNum.



3. Draw the overlay

In addition to drawing multi-axis graphs, you can also draw multiple curves in the same graph

t = np.arange(0., 5., 0.02)
y1=t
y2=t**2
y3=t**3
plt.plot(t, y1, 'r-', t, y2, 'b--', t, y3, 'g:')
plt.show()


4. Draw multi-style diagrams

First give a set of data

x = [1, 2, 3, 4, 5]
y = [2.3, 3.4, 1.2, 6.6, 7.0]

1) Curve graph

That is the plot of the first part

2) Scatter plot

plt.scatter(x, y, color='r', marker='+')
plt.show()

See the color and marker commonly used by scatter()

https://blog.csdn.net/qiu931110/article/details/68130199


3) Fan chart

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

labels='frogs','hogs','dogs','logs'
sizes=15,20,45,10
colors='yellowgreen','gold','lightskyblue','lightcoral'
explode=0,0.2,0,0
plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.1f%%',shadow=True,startangle=50)
plt.axis('equal')
plt.show()

Where explode is the separation factor, the default is 0, and 0.2 is 0.2 times the length of the radius

autopct='%1.1f%%' means 1 decimal place after the decimal point

When shadow is True, there is a shadow and a three-dimensional effect, which I personally think looks better.

startangle is the starting angle. The reference system is similar to the two-dimensional coordinate system, and counterclockwise is positive.


4) Histogram

plt.figure(figsize=(9,6))
n = 8
X = np.arange(n)+1
#X is 1,2,3,4,5,6,7,8, the number of bars
# numpy.random.uniform(low=0.0, high=1.0, size=None), normal
#uniform uniformly distributed random numbers, normal is a normally distributed random number, 0.5-1 uniformly distributed number, a total of n
Y1 = np.random.uniform(0.5,1.0,n)
Y2 = np.random.uniform(0.5,1.0,n)
plt.bar(X,Y1,width = 0.35,facecolor = 'lightskyblue',edgecolor = 'white')
#width: the width of the column
plt.bar(X+0.35,Y2,width = 0.35,facecolor = 'yellowgreen',edgecolor = 'white')
#Horizontal histogram plt.barh, the width in the attribute becomes the height
#Use + when playing two sets of data
#facecolor The color to fill in the histogram
#edgecolor is the color of the border
#If you want to type a set of data to the bottom, use a negative sign before the data
#plt.bar(X, -Y2, width=width, facecolor='#ff9999', edgecolor='white')
#Add text to the image
for x,y in zip(X,Y1):
    plt.text(x, y, '%.2f' % y, ha='center', va= 'bottom')

for x,y in zip(X,Y2):
    plt.text(x+0.35, y, '%.2f' % y, ha='center', va= 'bottom')
plt.ylim(0,+1.25)
plt.show()


5. Some setup tools

1) plt.text() adds text description

  • text() can add text anywhere in the figure and supports LaTex syntax
  • xlable(), ylable() for adding x-axis and y-axis labels
  • title() is used to add the title of the graph

2) plt.axis() sets the x, y axis range

plt.axis([Xmin,Xmax,Ymin,Ymax])

3) plt.annotate() text annotation

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.0),)#shrink is the shrinkage index
plt.ylim(-2,2)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Sample')
plt.show()



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325608837&siteId=291194637