This is the 7th day of my participation in the Gwen Challenge.
The Matplotlib library is introduced before the diagram is drawn. The corresponding code is usually written as “import matplotlib.pyplot asplt” to give the abbreviation to the library, and then the diagram is drawn by calling the required function with PLT as the prefix. For example, the plt.plot() function is used to plot line charts, the plt.bar() function is used to plot bar charts, the plt.pie() function is used to plot pie charts, etc. This section uses line charts, bar charts, scatter charts, and histograms as examples to explain the basic drawing methods of charts.
1. Draw a line chart
A line plot can be drawn using the plt.plot() function, shown below.
> > > import matplotlib. Pyplot as PLT > > > x = [1, 2, 3] > > > y = minus [2] > > > PLT. The plot (x, y) > > > PLT, show ()Copy the code
Note that plt.show() is used to show the drawing effect, as shown below.
If you want x and y to be mathematically related, but lists are not mathematically easy to calculate, you can use the NumPy library to introduce a one-dimensional array to do the math, as shown below.
Import numpy as np import matplotlib.pyplot as PLT x1 = np.array([1,2,3]) y1 =x1 +1 plt.plot(x1,y1) y2=x1*2 plt.plot(x1,y2,color = 'red',linewidth=3,linestyle='--') plt.show()Copy the code
Here, NumPy library is used to generate a one-dimensional array X1, and the operability of the array is used to generate y1 and y2. The two lines are drawn on a chart, and the final running result is shown in the figure below.
2. Draw a bar chart
A bar graph can be drawn using the plt.bar() function, shown below.
Import matplotlib.pyplot as PLT x = [1,2,3,4,5] y = [5,4,3,2,1] plt.bar(x,y) plt.show()Copy the code
The running result is shown in the figure below.
3. Draw a scatter plot
Use plt.scatter() to draw scatter graphs, as shown below.
import matplotlib.pyplot as plt
import numpy as np
x=np.random.rand(10)
y=np.random.rand(10)
plt.scatter(x,y)
plt.show()
Copy the code
Use Np.random. Rand (10) to generate 10 random numbers between 0 and 1, and the running results are shown in the figure below.
4. Draw a histogram
Histograms are divided into frequency histograms and frequency histograms. The abscissa is the relevant data, and the ordinate is the frequency or frequency of the data. The histogram can be drawn using the plt.hist() function, as shown below.
import matplotlib.pyplot as plt
import numpy as np
data = np.random.randn(10000)
plt.hist(data,bins=40,edgecolor='black')
plt.show()
Copy the code
Np.random.randn (10000) is used to randomly generate 10000 data subject to standard normal distribution (mean value is 0, standard deviation is 1), and the running results are shown in the figure below. The X-axis represents the randomly generated data, and the Y-axis represents the number of occurrences of the data, that is, frequency. In addition, if you want to plot the frequency histogram, you can set the density parameter to 1.