Python Matplotlib库入门指南
Matplotlib简介
Matplotlib是一个Python工具箱,用于科学计算的数据可视化。借助它,Python可以绘制如Matlab和Octave多种多样的数据图形。最初是模仿了Matlab图形命令, 但是与Matlab是相互独立的.
通过Matplotlib中简单的接口可以快速的绘制2D图表
初试Matplotlib
Matplotlib中的pyplot子库提供了和matlab类似的绘图API.
代码如下:
import matplotlib.pyplot as plt #导入pyplot子库
plt.figure(figsize=(8, 4)) #创建一个绘图对象, 并设置对象的宽度和高度, 如果不创建直接调用plot, Matplotlib会直接创建一个绘图对象
plt.plot([1, 2, 3, 4]) #此处设置y的坐标为[1, 2, 3, 4], 则x的坐标默认为[0, 1, 2, 3]在绘图对象中进行绘图, 可以设置label, color和linewidth关键字参数
plt.ylabel('some numbers') #给y轴添加标签, 给x轴加标签用xlable
plt.title("hello"); #给2D图加标题
plt.show() #显示2D图
基础绘图
绘制折线图
与所选点的坐标有关
代码如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
plt.plot(x, y, '-*r') # 虚线, 星点, 红色
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()
更改线的样式查看plot函数参数设置
多线图
只需要在plot函数中传入多对x-y坐标对就能画出多条线
代码如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
z = [1, 2, 3, 4, 5, 6]
plt.plot(x, y, '--*r', x, z, '-.+g')
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.title("hello world")
plt.show()
柱状图
代码如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
z = [1, 2, 3, 4, 5, 6]
plt.bar(x, y)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()
子图
subplot()函数指明numrows行数, numcols列数, fignum图个数. 图的个数不能超过行数和列数之积
代码如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
z = [1, 2, 3, 4, 5, 6]
plt.figure(1)
plt.subplot(211)
plt.plot(x, y, '-+b')
plt.subplot(212)
plt.plot(x, z, '-.*r')
plt.show()
文本添加
当需要在图片上调价文本时需要使用text()函数, 还有xlabel(), ylabel(), title()函数
text()函数返回matplotlib.text.Text, 函数详细解释
代码如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
plt.plot(x, y, '-.*r')
plt.text(1, 2, "I'm a text") //前两个参数表示文本坐标, 第三个参数为要添加的文本
plt.show()
图例简介
legend()函数实现了图例功能, 他有两个参数, 第一个为样式对象, 第二个为描述字符
代码如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend(handles=[line_up, line_down])
plt.show()
或者调用set_label()添加图例
代码如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
line, = plt.plot([1, 2, 3])
line.set_label("Label via method")
plt.legend()
plt.show()
同时对多条先添加图例
代码如下:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
line1, = plt.plot([1, 2, 3])
line2, = plt.plot([3, 2, 1], '--b')
plt.legend((line1, line2), ('line1', 'line2'))
plt.show()
更多图例设置可以参考官方图例教程

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

The H5 page needs to be maintained continuously, because of factors such as code vulnerabilities, browser compatibility, performance optimization, security updates and user experience improvements. Effective maintenance methods include establishing a complete testing system, using version control tools, regularly monitoring page performance, collecting user feedback and formulating maintenance plans.

Although distinct and distinct are related to distinction, they are used differently: distinct (adjective) describes the uniqueness of things themselves and is used to emphasize differences between things; distinct (verb) represents the distinction behavior or ability, and is used to describe the discrimination process. In programming, distinct is often used to represent the uniqueness of elements in a collection, such as deduplication operations; distinct is reflected in the design of algorithms or functions, such as distinguishing odd and even numbers. When optimizing, the distinct operation should select the appropriate algorithm and data structure, while the distinct operation should optimize the distinction between logical efficiency and pay attention to writing clear and readable code.

PS "Loading" problems are caused by resource access or processing problems: hard disk reading speed is slow or bad: Use CrystalDiskInfo to check the hard disk health and replace the problematic hard disk. Insufficient memory: Upgrade memory to meet PS's needs for high-resolution images and complex layer processing. Graphics card drivers are outdated or corrupted: Update the drivers to optimize communication between the PS and the graphics card. File paths are too long or file names have special characters: use short paths and avoid special characters. PS's own problem: Reinstall or repair the PS installer.

How to obtain dynamic data of 58.com work page while crawling? When crawling a work page of 58.com using crawler tools, you may encounter this...

Copying and pasting the code is not impossible, but it should be treated with caution. Dependencies such as environment, libraries, versions, etc. in the code may not match the current project, resulting in errors or unpredictable results. Be sure to ensure the context is consistent, including file paths, dependent libraries, and Python versions. Additionally, when copying and pasting the code for a specific library, you may need to install the library and its dependencies. Common errors include path errors, version conflicts, and inconsistent code styles. Performance optimization needs to be redesigned or refactored according to the original purpose and constraints of the code. It is crucial to understand and debug copied code, and do not copy and paste blindly.

Detailed explanation of JavaScript code line-breaking skills When writing JavaScript code, we often encounter a line of code that is too long, which not only affects the readability of the code...

1.0.1 Preface This project (including code and comments) was recorded during my self-taught Rust. There may be inaccurate or unclear statements, please apologize. If you benefit from it, it's even better. 1.0.2 Why is RustRust reliable and efficient? Rust can replace C and C, with similar performance but higher security, and does not require frequent recompilation to check for errors like C and C. The main advantages include: memory security (preventing null pointers from dereferences, dangling pointers, and data contention). Thread-safe (make sure multi-threaded code is safe before execution). Avoid undefined behavior (e.g., array out of bounds, uninitialized variables, or access to freed memory). Rust provides modern language features such as generics
