You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib添加按钮后无法绘图的多线程程序问题排查

问题分析与解决方案

你遇到的问题核心是手动添加按钮轴后,绘图上下文被切换到了按钮的小轴上,导致曲线实际画在了看不见的地方。

咱们拆解一下原因:

  • 当你执行ax = plt.axes([0.0, 0.0, 0.2, 0.1])创建按钮的轴时,Matplotlib会自动把这个新轴设置为当前的绘图轴。
  • 之后的adjustedTargetAskli, = plt.plot([], [], 'r-')是在当前轴(也就是按钮的小轴)上创建曲线,而不是你原本用来绘图的axes(111子图)。所以后续更新数据时,曲线其实在按钮轴上,但这个轴很小,根本看不到,看起来就像“无法绘图”。

修复方案(两种可选)

方案一:明确指定在目标轴上绘图

直接用axes.plot()代替plt.plot(),确保曲线画在正确的子图轴上:

import matplotlib.pyplot as plt
from matplotlib.widgets import Button

def buttonPush(event):
    print("Pushed the button!")

def plotGraph():
    global adjustedTargetAskHistory, TimeStampHistory
    plt.ion()
    fig = plt.figure()
    axes = fig.add_subplot(111)
    plt.xlabel('Time')
    
    # 创建按钮轴
    ax_button = plt.axes([0.0, 0.0, 0.2, 0.1])
    bcut = Button(ax_button,'Update', color='red', hovercolor='green')
    bcut.on_clicked(buttonPush)
    
    axes.set_autoscale_on(True)
    axes.autoscale_view(True,True,True)
    # 关键:用axes.plot在指定轴上创建曲线
    adjustedTargetAskli, = axes.plot([], [], 'r-')
    
    while True:
        adjustedTargetAskli.set_data(TimeStampHistory, adjustedTargetAskHistory)
        axes.relim()
        axes.autoscale_view(True,True,True)
        plt.pause(2)

方案二:切换回原绘图轴

如果坚持用plt.plot(),可以在创建按钮轴后,用plt.sca(axes)把当前轴切回原来的绘图轴:

import matplotlib.pyplot as plt
from matplotlib.widgets import Button

def buttonPush(event):
    print("Pushed the button!")

def plotGraph():
    global adjustedTargetAskHistory, TimeStampHistory
    plt.ion()
    fig = plt.figure()
    axes = fig.add_subplot(111)
    plt.xlabel('Time')
    
    # 创建按钮轴
    ax_button = plt.axes([0.0, 0.0, 0.2, 0.1])
    bcut = Button(ax_button,'Update', color='red', hovercolor='green')
    bcut.on_clicked(buttonPush)
    
    # 关键:切换回原来的绘图轴
    plt.sca(axes)
    
    axes.set_autoscale_on(True)
    axes.autoscale_view(True,True,True)
    adjustedTargetAskli, = plt.plot([], [], 'r-')
    
    while True:
        adjustedTargetAskli.set_data(TimeStampHistory, adjustedTargetAskHistory)
        axes.relim()
        axes.autoscale_view(True,True,True)
        plt.pause(2)

两种方案都能解决问题,推荐第一种,因为明确指定绘图轴的方式更清晰,不容易出错。

内容的提问来源于stack exchange,提问作者Iorek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:27:27