Home Backend Development Python Tutorial Detailed explanation of matplotlib drawing library in Python

Detailed explanation of matplotlib drawing library in Python

Jun 10, 2023 pm 09:42 PM
python matplotlib Drawing library

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

  1. Import Matplotlib

Before using matplotlib, you need to import it first. Usually the following code is used to import:

import matplotlib.pyplot as plt
Copy after login

Among them, plt is a conventional name used to simplify the use of matplotlib.

  1. 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()
Copy after login

When no parameters are passed, a window with a size of (8, 6) inches is created by default.

  1. 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()
Copy after login

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

  1. 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()
Copy after login

where x ranges from 0 to 10 with a step size of 0.1, and y is the corresponding sine function value.

  1. 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()
Copy after login

where x and y are both random numbers of length 50.

  1. 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()
Copy after login

where x is the category and y is the numerical size under each category.

  1. 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()
Copy after login

where x is a random number of length 1000.

  1. 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()
Copy after login

where sizes is the size of each category, and labels is the name of each category.

3. Matplotlib advanced

  1. 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()
Copy after login
  1. 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()
Copy after login

Among them, the label parameter is used to distinguish For different data sets, the legend function is used to display legends.

  1. 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()
Copy after login

Among them, r- - represents a red dotted line, and the linewidth parameter is used to set the line width.

  1. 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()
Copy after login

Among them, the subplot function accepts 3 parameters, representing the number of lines respectively. , column number and sub-figure serial number.

  1. Save the graphics

Use the savefig function to save the graphics as a file:

plt.plot(x, y)
plt.savefig("figure.png")
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1254
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles