Pyqtgraph问题:如何更新X轴数值而非让X轴滚动
解决PyQtGraph实时绘图X轴固定范围且更新数值的问题
问题分析
当前代码每次调用setData都会传入全部历史数据,导致X轴自动扩展并滚动。要实现**固定X轴窗口宽度、随新数据更新X轴数值(视窗平移)**的效果,需要手动控制X轴显示范围,并按需裁剪历史数据。
修改方案
1. 初始化时补充参数设置
在绘图初始化部分,添加X轴固定窗口宽度的配置,并初始化数据存储结构:
# Create Plot Widget self.scrolling_timestamp_plot_widget = pg.PlotWidget(axisItems={'bottom': TimeAxisItem(orientation='bottom')}) # Enable/disable plot squeeze (Fixed axis movement) self.scrolling_timestamp_plot_widget.plotItem.setMouseEnabled(x=False, y=False) self.scrolling_timestamp_plot_widget.setTitle('Signal 1 ') self.scrolling_timestamp_plot_widget.setLabel('left', 'Value') self.scrolling_timestamp_plot_widget.setLabel('bottom', 'Time (s)') # 新增:设置X轴固定显示窗口宽度(单位:秒,可按需调整) self.x_window_width = 10.0 # 初始化数据列表 self.data = [] self.scrolling_timestamp_plot = self.scrolling_timestamp_plot_widget.plot() self.scrolling_timestamp_plot.setPen("r")
2. 重写plot_updater函数
在绘图更新函数中,添加X轴范围控制和数据裁剪逻辑:
def plot_updater(self): self.data_point = float(self.current_position_value) current_time = self.timestamp.elapsed() self.data.append({'x': current_time, 'y': self.data_point }) # 裁剪历史数据:只保留X轴窗口范围内的数据,提升性能 window_start_time = current_time - self.x_window_width self.data = [item for item in self.data if item['x'] >= window_start_time] # 更新绘图数据 x_data = [item['x'] for item in self.data] y_data = [item['y'] for item in self.data] self.scrolling_timestamp_plot.setData(x=x_data, y=y_data) # 强制设置X轴显示范围,实现窗口平移、数值更新的效果 self.scrolling_timestamp_plot_widget.setXRange(window_start_time, current_time, padding=0)
关键说明
- 固定窗口宽度:通过
self.x_window_width设定要显示的时间长度,确保X轴始终展示最近指定时长的数据。 - 数据裁剪:过滤超出窗口范围的旧数据,避免数据量累积导致性能下降。
- 手动控制X轴范围:每次更新后调用
setXRange锁定显示区间,实现X轴数值随新数据更新、而非滚动的效果。
如果需要X轴从0开始持续扩展(不裁剪旧数据),只需将setXRange的参数改为(0, current_time),同时移除数据裁剪逻辑即可。
内容的提问来源于stack exchange,提问作者pedro Diamand
相关产品推荐
相关产品推荐

