如何在PyQtGraph中裁剪ViewBox空白区域优化X轴断裂图表
实现X轴断裂区域的空白裁剪(PyQtGraph)
完全可行,以下两种方案可解决你的需求:
方案1:使用PyQtGraph内置BrokenAxis组件
PyQtGraph提供BrokenAxis类专门处理断裂轴场景,它会自动隐藏轴上的空白区间,同时保留断裂标记提示数据不连续。
修改后的测试代码:
from PySide2.QtWidgets import QApplication, QMainWindow import pyqtgraph as pg import sys class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.graphWidget = pg.PlotWidget() self.setCentralWidget(self.graphWidget) # 创建断裂X轴,指定需隐藏的空白区间[3.5, 6.5] x_axis = pg.BrokenAxis(orientation='bottom', breaks=[(3.5, 6.5)]) self.graphWidget.setAxisItems({'bottom': x_axis}) # 原始数据无需修改,直接绘制 x1 = [1,2,3] y1 = [30,27,34] self.plotDataItem1 = pg.PlotDataItem(x1, y1) self.graphWidget.addItem(self.plotDataItem1) x2 = [7,8,9,10] y2 = [29,32,35,45] self.plotDataItem2 = pg.PlotDataItem(x2, y2) self.graphWidget.addItem(self.plotDataItem2) # 自动调整视图范围,聚焦有效数据 self.graphWidget.autoRange() app = QApplication(sys.argv) w = MainWindow() w.show() app.exec_()
方案2:手动映射X轴数据(自定义刻度标签)
如果需要更灵活的布局控制,可以手动将第二段数据的X值映射到连续区间,再自定义坐标轴刻度标签,让ViewBox完全消除空白区域。
修改后的测试代码:
from PySide2.QtWidgets import QApplication, QMainWindow import pyqtgraph as pg import sys class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.graphWidget = pg.PlotWidget() self.setCentralWidget(self.graphWidget) # 第一段原始数据 x1 = [1,2,3] y1 = [30,27,34] self.plotDataItem1 = pg.PlotDataItem(x1, y1) self.graphWidget.addItem(self.plotDataItem1) # 第二段数据映射:把7-10映射为4-7,填补3之后的连续区间 x2_original = [7,8,9,10] y2 = [29,32,35,45] x2_mapped = [x - 3 for x in x2_original] # 7→4,8→5,以此类推 self.plotDataItem2 = pg.PlotDataItem(x2_mapped, y2) self.graphWidget.addItem(self.plotDataItem2) # 自定义X轴刻度:将映射后的数值替换为原始数据标签 x_axis = self.graphWidget.getAxis('bottom') tick_positions = x1 + x2_mapped tick_labels = [str(x) for x in x1] + [str(x) for x in x2_original] x_axis.setTicks([[(pos, label) for pos, label in zip(tick_positions, tick_labels)]]) # 调整视图范围到映射后的连续区间 self.graphWidget.setXRange(0.5, 7.5) app = QApplication(sys.argv) w = MainWindow() w.show() app.exec_()
方案对比
- 方案1更简洁,保留断裂轴的视觉提示,适合需要明确展示数据不连续性的场景。
- 方案2完全消除空白,视觉呈现为连续图表,适合紧凑布局需求,但需手动处理数据映射和刻度标签。
内容的提问来源于stack exchange,提问作者Nikolas
相关产品推荐
相关产品推荐

