您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python中绘图库Matplotlib怎么用
Matplotlib是Python中最流行的2D绘图库,广泛应用于数据可视化、科学计算和机器学习等领域。本文将详细介绍Matplotlib的安装、基础用法、常见图表绘制以及高级定制技巧。
## 目录
1. [Matplotlib简介](#matplotlib简介)
2. [安装与配置](#安装与配置)
3. [基础绘图](#基础绘图)
4. [常见图表类型](#常见图表类型)
5. [多图与子图](#多图与子图)
6. [样式与美化](#样式与美化)
7. [高级功能](#高级功能)
8. [实际应用案例](#实际应用案例)
9. [常见问题解答](#常见问题解答)
---
## Matplotlib简介
Matplotlib由John D. Hunter于2003年创建,现已成为Python数据可视化的标准库。主要特点包括:
- 支持多种输出格式(PNG, PDF, SVG等)
- 高度可定制的图形元素
- 与NumPy、Pandas无缝集成
- 提供面向对象和MATLAB风格两种API
```python
import matplotlib.pyplot as plt
import numpy as np
pip install matplotlib
import matplotlib.pyplot as plt
plt.style.use('seaborn') # 使用seaborn风格
%matplotlib inline # Jupyter Notebook魔法命令
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure(figsize=(8, 4))
plt.plot(x, y, label='sin(x)', color='blue', linestyle='--')
plt.title("Sine Wave")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.legend()
plt.grid(True)
plt.show()
figure
: 画布容器axes
: 实际绘图区域axis
: 坐标轴title/label
: 标题和标签legend
: 图例x = np.random.randn(100)
y = x + np.random.randn(100)*0.5
plt.scatter(x, y, alpha=0.6, c='green', marker='o')
plt.title("Scatter Plot")
labels = ['A', 'B', 'C']
values = [15, 30, 45]
plt.bar(labels, values, color=['red', 'green', 'blue'])
data = np.random.randn(1000)
plt.hist(data, bins=30, edgecolor='black')
sizes = [15, 30, 45, 10]
plt.pie(sizes, labels=['A', 'B', 'C', 'D'], autopct='%1.1f%%')
plt.subplot(2, 1, 1) # 2行1列第1个
plt.plot(x, y)
plt.subplot(2, 1, 2)
plt.scatter(x, y)
fig, axes = plt.subplots(2, 2, figsize=(10, 6))
axes[0,0].plot(x, y)
axes[0,1].bar(labels, values)
plt.plot(x, y,
color='#FF5733', # HEX颜色
linestyle=':',
linewidth=2,
marker='o',
markersize=5)
print(plt.style.available) # 查看可用样式
plt.style.use('ggplot')
plt.rcParams.update({
'font.size': 12,
'axes.titlesize': 16,
'axes.labelsize': 14
})
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)
ax.scatter(x, y, z)
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
line, = ax.plot([], [])
def init():
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
return line,
def update(frame):
line.set_data(x[:frame], y[:frame])
return line,
ani = FuncAnimation(fig, update, frames=len(x), init_func=init, blit=True)
import pandas as pd
data = pd.read_csv('stock.csv', parse_dates=['Date'])
plt.figure(figsize=(12, 6))
plt.plot(data['Date'], data['Close'], label='Close Price')
plt.fill_between(data['Date'], data['Low'], data['High'], alpha=0.2)
from sklearn.datasets import make_classification
X, y = make_classification(n_features=2, n_classes=3)
plt.scatter(X[:,0], X[:,1], c=y, cmap='viridis')
plt.colorbar()
plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] # Mac
plt.savefig('output.png', dpi=300, bbox_inches='tight')
plt.legend(loc='upper right', bbox_to_anchor=(1.3, 1))
Matplotlib提供了强大的数据可视化能力,本文涵盖了: - 基础绘图流程 - 10+种常见图表 - 样式美化技巧 - 高级功能应用 - 实际场景案例
通过不断实践,你将能够创建出专业级的可视化作品!
提示:建议结合官方文档(https://matplotlib.org/)深入学习更多高级功能 “`
(注:实际文章需要补充更多细节说明和示例代码,此处为精简版框架,完整5300字版本会扩展每个章节的详细说明、更多示例和注意事项)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。