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

如何自定义pyqtgraph热力图的轴标签、字体及颜色条?

PyQt+pyqtgraph 自定义热力图实现方案

以下是满足你需求的完整代码,针对三个核心需求做了针对性修改:

import numpy as np
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QMainWindow, 
                             QHBoxLayout)
from PyQt5.QtGui import QFont
import pyqtgraph as pg

pg.setConfigOption('background', 'lightgray')

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Heatmap")
        self.setStyleSheet("background-color: lightgray;")         
        self.resize(600, 500)

        # 主布局
        main_layout = QHBoxLayout()

        # 替换ImageView为PlotWidget+ImageItem,更灵活可控
        plot_widget = pg.PlotWidget()
        plot_widget.setAspectLocked(True)  # 保证热力图方块为正方形

        # 生成热力图数据
        data = np.random.rand(5,5)
        image_item = pg.ImageItem(data)
        plot_widget.addItem(image_item)

        # 自定义颜色映射
        colors = [(0, 0, 0),(4, 5, 61),(84, 42, 55),(15, 87, 60),(208, 17, 141),(255, 255, 255)]
        cmap = pg.ColorMap(pos=np.linspace(0.0, 1.0, 6), color=colors)
        image_item.setColorMap(cmap)

        # 设置坐标轴字符串标签及居中对齐
        labels = ['a','b','c','d','e']
        # 调整坐标轴范围,让每个单元格中心对应刻度位置
        plot_widget.setXRange(-0.5, 4.5)
        plot_widget.setYRange(-0.5, 4.5)
        # 绑定刻度位置与字符串标签
        ticks = [list(zip(range(5), labels))]
        plot_widget.getAxis('bottom').setTicks(ticks)
        plot_widget.getAxis('left').setTicks(ticks)

        # 调整标签字体类型和大小
        custom_font = QFont("Arial", 12)  # 可替换为其他字体,比如"微软雅黑"
        plot_widget.getAxis('bottom').setTickFont(custom_font)
        plot_widget.getAxis('left').setTickFont(custom_font)

        # 创建静态颜色条,替代原ImageView右侧控件
        color_bar = pg.ColorBarItem(values=(0, 1), colorMap=cmap)
        color_bar.setImageItem(image_item)

        # 布局分配空间,主图占比更大
        main_layout.addWidget(plot_widget, stretch=4)
        main_layout.addWidget(color_bar, stretch=1)

        # 设置主窗口中心部件
        central_widget = QWidget()
        central_widget.setLayout(main_layout)
        self.setCentralWidget(central_widget)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()

核心修改说明

  • 轴标签居中对齐:
    通过将坐标轴范围调整为(-0.5, 4.5),让5x5单元格的中心刚好对应0-4的刻度位置,再用setTicks把数值刻度替换为自定义字符串,实现标签与方块中心对齐。

  • 字体自定义:
    用QFont创建指定类型和大小的字体,通过坐标轴对象的setTickFont方法应用到轴标签上,可按需修改字体名称和字号。

  • 静态颜色条替换:
    放弃自带交互控件的ImageView,改用PlotWidget+ImageItem组合,搭配ColorBarItem生成静态色条,通过布局实现和主图的并排展示,完全移除原右侧的缩放、拖动控件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:31:15