Detailed explanation of matplotlib drawing library in Python
Python’s matplotlib drawing library is a very powerful data visualization tool. It can be used to draw various types of graphs, including line graphs, scatter plots, bar graphs, histograms, pie charts, and more. Due to its ease of learning and use, as well as community support, matplotlib has become one of the standard visualization tools in the Python scientific computing community. This article will introduce in detail how to use the matplotlib drawing library and how to draw common graphics.
1. Matplotlib basics
- Import Matplotlib
Before using matplotlib, you need to import it first. Usually the following code is used to import:
import matplotlib.pyplot as plt
Among them, plt is a conventional name used to simplify the use of matplotlib.
- Drawing window
Before drawing graphics, you need to create a drawing window. You can use the following code to create the simplest drawing window:
plt.figure()
When no parameters are passed, a window with a size of (8, 6) inches is created by default.
- Draw graphics
After creating the drawing window, you can start drawing graphics. For example, to draw a simple straight line, you can use the following code:
import numpy as np x = np.array([0, 1, 2, 3, 4]) y = np.array([0, 1, 2, 3, 4]) plt.plot(x, y) plt.show()
where np is an alias for the NumPy library used to generate data on the x and y axes. The plot function is used to draw straight lines, and the show function is used to display graphics. After running this code, a drawing window will pop up and display the straight line.
2. Common graph drawing methods
- Line graph
Line graph is a graph used to draw continuous data. It can be plotted using the plot function. For example, the following code will draw a sine function curve:
x = np.arange(0, 10, 0.1) y = np.sin(x) plt.plot(x, y) plt.show()
where x ranges from 0 to 10 with a step size of 0.1, and y is the corresponding sine function value.
- Scatter plot
A scatter plot is used to plot the relationship between two variables, such as X and Y coordinates. You can use the scatter function for drawing. For example, the following code will create a scatter plot of random data:
x = np.random.rand(50) y = np.random.rand(50) plt.scatter(x, y) plt.show()
where x and y are both random numbers of length 50.
- Histogram
The histogram is used to compare the numerical values under various categories. It can be drawn using the bar function. For example, the following code will draw a simple histogram:
x = ["A", "B", "C", "D", "E"] y = [10, 5, 8, 12, 7] plt.bar(x, y) plt.show()
where x is the category and y is the numerical size under each category.
- Histogram
Histogram is used to display the distribution of a set of data. It can be drawn using the hist function. For example, the following code will plot a histogram of random data:
x = np.random.randn(1000) plt.hist(x) plt.show()
where x is a random number of length 1000.
- Pie chart
The pie chart is used to display the proportion of various categories. You can use the pie function for drawing. For example, the following code will draw a simple pie chart:
labels = ["A", "B", "C", "D", "E"] sizes = [15, 30, 45, 10, 5] plt.pie(sizes, labels=labels) plt.show()
where sizes is the size of each category, and labels is the name of each category.
3. Matplotlib advanced
- Coordinate axis setting
Use xlabel, ylabel, and title functions to set the horizontal axis, vertical axis, and graphic title:
plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.title("Title") plt.plot(x, y) plt.show()
- Legend setting
Use the legend function to set the legend to distinguish different data sets:
x1 = np.arange(0, 10, 0.1) y1 = np.sin(x1) x2 = np.arange(0, 10, 0.1) y2 = np.cos(x2) plt.plot(x1, y1, label="sin") plt.plot(x2, y2, label="cos") plt.legend() plt.show()
Among them, the label parameter is used to distinguish For different data sets, the legend function is used to display legends.
- Formatting style settings
You can use the fmt parameter to set the style of the line, such as color, line shape and line width:
plt.plot(x, y, "r--", linewidth=2) plt.show()
Among them, r- - represents a red dotted line, and the linewidth parameter is used to set the line width.
- Subplot settings
You can use the subplot function to draw multiple subplots:
plt.subplot(2, 2, 1) plt.plot(x, y) plt.subplot(2, 2, 2) plt.scatter(x, y) plt.subplot(2, 2, 3) plt.bar(x, y) plt.subplot(2, 2, 4) plt.hist(x) plt.show()
Among them, the subplot function accepts 3 parameters, representing the number of lines respectively. , column number and sub-figure serial number.
- Save the graphics
Use the savefig function to save the graphics as a file:
plt.plot(x, y) plt.savefig("figure.png")
The parameters represent the file name and path.
Conclusion
This article introduces the basic usage of matplotlib drawing library and the drawing methods of common graphics, as well as some advanced techniques. As an indispensable part of Python scientific computing, learning the matplotlib drawing library will help you better perform data visualization and data analysis.
The above is the detailed content of Detailed explanation of matplotlib drawing library in Python. For more information, please follow other related articles on the PHP Chinese website!

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Atom editor mac version download
The most popular open source editor
