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

Matplotlib仅能绘制最后一个子图问题求助

问题根源与修复方案

你的代码里只有最后一个子图能显示的核心原因是:你用fig.gca()来更新轴范围,但gca()只会选中最后创建的子图(也就是axis2),第一个子图axis1的数据更新后,轴范围没有自动调整,导致数据被“藏”在当前轴范围外,看起来像是没显示。

下面是修复后的完整代码,关键修改点已标注:

import socket
import sys
import time
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from datetime import datetime
matplotlib.use('Qt5Agg')

# TVAC IP and Port
target_host = "10.1.2.101"
target_port = 1

print()

# 尝试建立TCP连接
try:
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((target_host, target_port))
except socket.error:
    print("Socket Not Created!  ¯\\(°_o)/¯")
    sys.exit()
print("Socket Created   (⌐⊙_⊙)")
print()
print("Socket Connected To " + target_host)
print()

time.sleep(2)

# 命令定义
CMD_PRESSURE = "?VP"
CMD_TC = ["?T2", "?T12", "?T13", "?T14", "?T15", "?T16", "?T17", "?T18"]

# 回车符
CR = "\r"

def TVAC(cmd):
    try:
        # 发送命令并接收数据
        client.send(bytes(cmd + CR + '\0', 'ascii'))
        response = client.recv(1024).decode('ascii')
        if cmd == CMD_PRESSURE:
            # 处理压力数据
            val = float(response[3:-1])
        else:
            # 处理热电偶数据
            val = float(response[5:-1]) / 10
        print(val)
        return val
    except socket.error:
        print("Failed to send command")
        return np.nan  # 出错时返回NaN避免崩溃

# 创建绘图对象
fig = plt.figure()
axis_pressure = fig.add_subplot(211)
axis_temp = fig.add_subplot(212)

# 数据存储列表
times = []
pressure_data = []
tc_data = [[] for _ in range(8)]  # 8个热电偶数据

# 创建绘图线条
line_pressure, = axis_pressure.plot_date([], [], "-", color='red')
lines_temp = []
colors = ['blue', 'green', 'purple', 'yellow', 'black', 'orange', 'grey', 'red']
for color in colors:
    line, = axis_temp.plot_date([], [], "-", color=color)
    lines_temp.append(line)

# 配置子图样式
axis_pressure.grid(axis='y')
axis_temp.grid(axis='y')
axis_pressure.set_title("Pressure")
axis_temp.set_title("Temperature")

def update(frame):
    current_time = datetime.now()
    times.append(current_time)
    
    # 获取最新数据
    pressure = TVAC(CMD_PRESSURE)
    pressure_data.append(pressure)
    
    for i, cmd in enumerate(CMD_TC):
        tc_val = TVAC(cmd)
        tc_data[i].append(tc_val)
    
    # 更新压力子图线条数据
    line_pressure.set_data(times, pressure_data)
    # 更新温度子图所有线条数据
    for i, line in enumerate(lines_temp):
        line.set_data(times, tc_data[i])
    
    # 关键修复:分别更新两个子图的轴范围
    axis_pressure.relim()
    axis_pressure.autoscale_view()
    axis_temp.relim()
    axis_temp.autoscale_view()
    
    # 设置刻度格式
    axis_pressure.ticklabel_format(axis='y', style='sci', scilimits=(0,0))
    axis_temp.ticklabel_format(axis='y', style='plain', scilimits=(0,0))
    
    # 返回所有需要更新的线条对象
    return [line_pressure] + lines_temp

anim = FuncAnimation(fig, update, cache_frame_data=False)
plt.show()

关键修改说明

  1. 轴范围更新:去掉fig.gca(),改为直接调用每个子图的relim()和autoscale_view()方法,确保两个子图都会根据新数据自动调整轴范围。
  2. 变量优化:把分散的热电偶数据列表改成统一的tc_data,命令也用列表管理,代码更简洁易维护。
  3. 容错处理:在TVAC函数出错时返回NaN,避免单次通信失败导致动画崩溃。
  4. 冗余移除:合并重复的时间列表,所有子图共用同一个时间轴数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:06:05