Matplotlib

本文详细介绍了Matplotlib库的核心概念,包括Figure和Axes的使用,如何调整子图距离,以及Matplotlib的后端和交互式模式。此外,还探讨了事件处理机制,提供了一个用例展示如何响应鼠标操作,并解释了在交互和非交互模式下如何显示和管理图像。

Matplotlib

概念

Figure :Figure 就是一张图像,一个窗口。其中可以包括多个子图。由 plt.figure() 创建。

Axes:一张具体的图。绘制函数都在这个类下。

fig = plt.figure(figsize=(6, 6)) # 创建图片
ax1 = fig.add_subplot(121) # 子图, grid 1
ax1.set_xlabel('x') # 设置图标
ax1.set_ylabel('output1')
ax2 = fig.add_subplot(122)
ax2.set_xlabel('x')
ax2.set_ylabel('output2')
x = np.linspace(0, 3, 20)
y = np.sin(x)
z = np.cos(x)

ax1.plot(x, y) # 绘制
ax2.plot(x, z)
fig.show()

Figure

每一个 Figure 创建时都会在后台记录,以免被回收释放。可以用 plt.close() 或者 plt.close('all') 释放。

创建函数 plt.figure()

  1. num 指定了 Figure 的标号(相当于 descriptor),如果重合则会返回之前的 Figure
  2. clear 清除指定的图片。

Axes

调整子图距离

调用函数:

plt.subplots_adjust(left=0.15,bottom=0.1,top=0.9,right=0.95,hspace=.4,wspace=.75)

此函数是在所有绘制完成后,显示之前调用

后端

后端使 Matplotlib 适用于不同的应用场景。设置后端方式:

  1. The rcParams["backend"] (default: ‘agg’) parameter in your matplotlibrc file
  2. The MPLBACKEND environment variable
  3. The function matplotlib.use()

交互式

在显示图片时,交互模式下终端仍然能输入命令。适用 plt.ion()plt.ioff() 控制。在交互式模式下,ax.plot() 后会立即显示图片,程序继续执行。程序可以继续在 Axes 上绘制图片,并使用函数 plt.draw() 显示。

  • whether created figures are automatically shown
  • whether changes to artists automatically trigger re-drawing existing figures
  • when pyplot.show() returns if given no arguments: immediately, or after all of the figures have been closed

非交互模式下,plt.show() 显示图片并阻塞。关闭该窗口后,程序才会继续执行。

  • newly created figures and changes to figures are not displayed until
    • pyplot.show() is called
    • pyplot.pause() is called
    • FigureCanvasBase.flush_events() is called
  • pyplot.show() runs the GUI event loop and does not return until all the plot windows are closed

操作函数(utils)

事件处理

事件处理本质上都是循环(Event Loop),等待用户输入并响应。

回调函数绑定:

cid = fig.canvas.mpl_connect('button_press_event', onclick) # connect
fig.canvas.mpl_disconnect(cid) # disconnect

事件列表

回调函数中 event 属性。 说明:

  1. xdata 是在绘制的坐标轴中;x 是在整个 Figure 中的坐标。
  2. inaxes 鼠标所在的 Axes 对象,用于处理当前的 Axes 图形。

回调函数示例:

def onclick(event):
    print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
          ('double' if event.dblclick else 'single', event.button,
           event.x, event.y, event.xdata, event.ydata))

Use Case

  • 鼠标拖动

key_press_event / key_release_event / motion_notify_event

按下时设置标志位,拖动时由此进行偏移计算,释放时复位标志位,释放资源。示例可见

阻塞并读取输入

Class BlockingMouseInput 阻塞并读取鼠标输入。左键选择,右键删除,中间键退出返回。可以在初始化中设置鼠标按键。

keys = blocking_input.BlockingMouseInput(fig)
events = keys(8) # 阻塞,并读取8个鼠标输入,返回坐标 List[tuple]
### Matplotlib 使用指南 Matplotlib 是一个功能强大的 Python 数据可视化库,广泛应用于数据分析、科学计算和机器学习等领域。以下是关于 Matplotlib使用指南,包括安装、基本绘图方法以及一些常见图表类型的绘制示例。 #### 安装 Matplotlib使用 Matplotlib 之前,需要确保已正确安装该库。可以通过以下命令安装 Matplotlib: ```bash pip install matplotlib ``` 如果使用的是 Anaconda 环境,则可以使用以下命令进行安装[^3]: ```bash conda install matplotlib ``` #### 导入 Matplotlib 在代码中使用 Matplotlib 时,通常会将其 `pyplot` 模块导入并命名为 `plt`,这是一种常见的惯例[^2]: ```python import matplotlib.pyplot as plt ``` #### 基本绘图方法 Matplotlib 提供了丰富的绘图功能,以下是一些基本的绘图方法和示例: 1. **绘制简单的折线图** ```python import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] plt.plot(x, y) # 绘制折线图 plt.title("Simple Line Plot") # 设置标题 plt.xlabel("X-axis") # 设置 X 轴标签 plt.ylabel("Y-axis") # 设置 Y 轴标签 plt.show() # 显示图形 ``` 2. **绘制散点图** ```python import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] plt.scatter(x, y) # 绘制散点图 plt.title("Scatter Plot") # 设置标题 plt.xlabel("X-axis") # 设置 X 轴标签 plt.ylabel("Y-axis") # 设置 Y 轴标签 plt.show() # 显示图形 ``` 3. **绘制柱状图** ```python import matplotlib.pyplot as plt categories = ['A', 'B', 'C', 'D'] values = [3, 7, 2, 5] plt.bar(categories, values) # 绘制柱状图 plt.title("Bar Chart") # 设置标题 plt.xlabel("Categories") # 设置 X 轴标签 plt.ylabel("Values") # 设置 Y 轴标签 plt.show() # 显示图形 ``` #### 进阶功能 Matplotlib 不仅支持基本的图表类型,还提供了许多高级功能,例如子图布局、颜色定制和样式调整等。 1. **创建子图** ```python import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 2) # 创建 2x2 的子图布局 axs[0, 0].plot([1, 2, 3], [3, 2, 1]) # 第一个子图 axs[0, 1].scatter([1, 2, 3], [1, 4, 9]) # 第二个子图 axs[1, 0].bar(['A', 'B', 'C'], [3, 7, 2]) # 第三个子图 axs[1, 1].hist([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]) # 第四个子图 plt.tight_layout() # 自动调整子图间距 plt.show() ``` 2. **自定义样式** Matplotlib 支持多种样式选项,可以通过以下方式应用预定义样式: ```python import matplotlib.pyplot as plt plt.style.use('ggplot') # 应用 ggplot 风格 x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] plt.plot(x, y) plt.show() ``` #### 官方资源 更多详细的教程和案例可以参考 Matplotlib 官网[^1]: - 官网地址:[https://matplotlib.org/index.html](https://matplotlib.org/index.html) - 示例画廊:[https://matplotlib.org/gallery/index.html](https://matplotlib.org/gallery/index.html)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值