matplotlib基本要掌握的内容并给出代码
时间: 2024-03-13 13:45:39 浏览: 21
好的,以下是一些 matplotlib 的基本要掌握的内容以及对应的代码示例:
1. 创建图形并添加子图
```python
import matplotlib.pyplot as plt
# 创建一个图形
fig = plt.figure()
# 添加一个子图
ax = fig.add_subplot(1, 1, 1)
# 显示图形
plt.show()
```
2. 添加标题、标签、注释和图例
```python
import matplotlib.pyplot as plt
# 创建数据
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
# 创建一个图形和子图
fig, ax = plt.subplots()
# 绘制折线图
ax.plot(x, y)
# 添加标题、标签、注释和图例
ax.set_title("My Plot")
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.annotate("Important Point", xy=(2, 8), xytext=(3, 10),
arrowprops=dict(facecolor="red", shrink=0.05))
ax.legend(["My Line"])
# 显示图形
plt.show()
```
3. 绘制线条、散点图、柱状图、饼图等常见图形
```python
import matplotlib.pyplot as plt
# 创建数据
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
# 绘制折线图
plt.plot(x, y)
# 绘制散点图
plt.scatter(x, y)
# 绘制柱状图
plt.bar(x, y)
# 绘制饼图
plt.pie(y)
# 显示图形
plt.show()
```
4. 自定义坐标轴的范围、刻度、标签和网格线等
```python
import matplotlib.pyplot as plt
# 创建数据
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
# 创建一个图形和子图
fig, ax = plt.subplots()
# 绘制折线图
ax.plot(x, y)
# 自定义坐标轴
ax.set_xlim(0, 5)
ax.set_ylim(0, 20)
ax.set_xticks([1, 2, 3, 4])
ax.set_yticks([0, 5, 10, 15, 20])
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.grid(True)
# 显示图形
plt.show()
```
5. 设置图形的样式、颜色和透明度等属性
```python
import matplotlib.pyplot as plt
# 创建数据
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
# 创建一个图形和子图
fig, ax = plt.subplots()
# 绘制折线图
ax.plot(x, y, linestyle="--", linewidth=2, marker="o", markersize=8,
markerfacecolor="blue", markeredgecolor="red", alpha=0.8)
# 设置图形属性
ax.set_title("My Plot")
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
# 显示图形
plt.show()
```
6. 处理日期和时间序列数据
```python
import matplotlib.pyplot as plt
import pandas as pd
# 读取数据
data = pd.read_csv("data.csv", parse_dates=["Date"])
# 创建一个图形和子图
fig, ax = plt.subplots()
# 绘制折线图
ax.plot(data["Date"], data["Value"])
# 设置坐标轴标签和网格线
ax.set_title("My Plot")
ax.set_xlabel("Date")
ax.set_ylabel("Value")
ax.grid(True)
# 显示图形
plt.show()
```
7. 保存图形为图片或 PDF 文件
```python
import matplotlib.pyplot as plt
# 创建数据
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
# 创建一个图形和子图
fig, ax = plt.subplots()
# 绘制折线图
ax.plot(x, y)
# 设置图形属性
ax.set_title("My Plot")
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
# 保存图形为 PNG 格式的图片
fig.savefig("my_plot.png")
# 保存图形为 PDF 文件
fig.savefig("my_plot.pdf")
# 显示图形
plt.show()
```