您可以先删除底部轴刻度标签,然后将每个条添加为具有适当宽度的 pg.InfiniteLine 对象。
使用AxisItem.setTicks(ticks)方法可以实现将y轴刻度标签改为r,g,b值。
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow
import pyqtgraph as pg
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
class ColorBarPlot(pg.GraphicsLayoutWidget):
def __init__(self):
super(ColorBarPlot, self).__init__()
self.p1 = pg.PlotItem()
self.addItem(self.p1)
self.p1.getAxis('bottom').setStyle(showValues=False)
def displayColors(self, colors):
self.p1.clear()
ticks = []
for i, color in enumerate(colors):
line = pg.InfiniteLine(
pos=i+1, # y value of the line
angle=0, # horizontal, 90 is vertical
pen=pg.mkPen(pg.mkColor(color[0], color[1], color[2]), width=15) # Set color
)
self.p1.addItem(line)
ticks.append((i+1, '{},{},{}'.format(color[0], color[1], color[2])))
self.p1.getAxis('left').setTicks([ticks])
if __name__ == "__main__":
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
app = QApplication([])
win = QMainWindow()
plot = ColorBarPlot()
win.setCentralWidget(plot)
plot.displayColors([[200, 200, 215], [161, 162, 172], [72, 45, 31], [116, 75, 33], [182, 182, 195], [103, 63, 26], [151, 152, 156], [211, 211, 228], [190, 191, 204], [98, 75, 49], [93, 51, 23], [135, 135, 135], [117, 107, 84], [163, 99, 35], [172, 173, 184], [172, 173, 184]])
win.show()
if (sys.flags.interactive != 1) or not hasattr(Qt.QtCore, "PYQT_VERSION"):
QApplication.instance().exec_()
Result