问题
Having a simple graphics layout with PyQtGraph in which the x-axis of the plots are linked together and the grid is displayed in both plots as well:
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
app = QtGui.QApplication([])
view = pg.GraphicsView()
l = pg.GraphicsLayout()
view.setCentralItem(l)
view.show()
view.resize(800,600)
p0 = l.addPlot(0, 0)
p0.showGrid(x = True, y = True, alpha = 0.3)
#p0.hideAxis('bottom')
p1 = l.addPlot(1, 0)
p1.showGrid(x = True, y = True, alpha = 0.3)
p1.setXLink(p0)
l.layout.setSpacing(0.)
l.setContentsMargins(0., 0., 0., 0.)
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
If I hide the x-axis in the first plot (uncommenting the p0.hideAxis('bottom')
line in the code) then the axis will be gone, but the grid will disappear too:
How could I force it to stay there? As both x-axis are linked together, I would expect that to be possible (the grid in the upper plot could be taken from the lower plot's x-axis).
回答1:
Instead of hiding the axis, try axis.setStyle(showValues=False)
.
(This might only be available in the development branch)
回答2:
So, this is complete code with the amendments:
#https://stackoverflow.com/questions/27100277/pyqtgraph-grid-with-linked-axes
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
app = QtGui.QApplication([])
view = pg.GraphicsView()
l = pg.GraphicsLayout()
view.setCentralItem(l)
view.show()
view.resize(800,600)
p0 = l.addPlot(0, 0)
p0.showGrid(x = True, y = True, alpha = 1.0)
#have no x-axis tickmark below the upper plot (coordinate 0,0)
#without these lines, there will be separate coordinate systems with a gap inbetween
ax0 = p0.getAxis('bottom') #get handle to x-axis 0
ax0.setStyle(showValues=False) #this will remove the tick labels and reduces gap b/w plots almost to zero
#there will be a double line separating the plot rows
p1 = l.addPlot(1, 0)
p1.showGrid(x = True, y = True, alpha = 1.0)
p1.setXLink(p0)
l.layout.setSpacing(0.)
l.setContentsMargins(0., 0., 0., 0.)
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
来源:https://stackoverflow.com/questions/27100277/pyqtgraph-grid-with-linked-axes