如何在GUI pyqt中更新热图的颜色栏?

时间:2018-10-28 17:27:03

标签: python matplotlib pyqt pyqt5 seaborn

我在使用热板和颜色条更新GUI时遇到问题,问题是我可以很好地更新热图,但是在每次更新中都添加了新的颜色条。 我的问题特别是与颜色栏有关,我尝试删除了颜色栏,但是,如果我将其从程序中消失了,则需要它。可以在附件的图像中看到问题。

class MainWindow(QtWidgets.QMainWindow):
    send_fig = QtCore.pyqtSignal(str)

    def __init__(self):
        super(MainWindow, self).__init__()

        self.main_widget = QtWidgets.QWidget(self)
        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)
        self.im=self.ax.images 

        self.canvas = FigureCanvas(self.fig)

        self.canvas.setSizePolicy(QtWidgets.QSizePolicy.Expanding, 
                                  QtWidgets.QSizePolicy.Expanding)
        self.canvas.updateGeometry()

        self.dropdown1 = QtWidgets.QComboBox()
        self.dropdown1.addItems(["Número de puntos", "Número de transacciones", "Valor promedio de las tx"])
        self.dropdown1.setCurrentIndex(2)

        self.dropdown1.currentIndexChanged.connect(self.update)

        #self.label = QtWidgets.QLabel("A plot:")

        self.layout = QtWidgets.QGridLayout(self.main_widget)
        self.layout.addWidget(QtWidgets.QLabel("Selecciona una categoría"))
        self.layout.addWidget(self.dropdown1)
        self.layout.addWidget(self.canvas)

        self.setCentralWidget(self.main_widget)
        self.show()
        self.update()

    def update(self):


        self.ax.clear()

        datosHeatMap = pd.read_csv(r"\file.csv")

        df = pd.DataFrame(datosHeatMap, columns =["id_comercio","HoraNumero","Hora","DiaNum","Día","Puntos","Transacciones","Clientes","Valor","Cargas","Redenciones"])
        puntos = []
        puntos.append(df.pivot("HoraNumero","DiaNum","Puntos").fillna(0).astype(float))
        puntos.append(df.pivot("HoraNumero","DiaNum","Transacciones").fillna(0).astype(float))
        puntos.append(df.pivot("HoraNumero","DiaNum","Valor").fillna(0).astype(float))

        dias=[]

        numDia = {0:"Lunes",1:"Martes",2:"Miercoles",3:"Jueves",4:"Viernes",5:"Sabado",6:"Domingo",}

        dias.append(list(puntos[0].columns))
        dias.append(list(puntos[1].columns))
        dias.append(list(puntos[2].columns))

        cat1_index = self.dropdown1.currentIndex()
        cat1_text = self.dropdown1.currentText()


        self.ax.set_title(cat1_text)

        sns.heatmap(puntos[cat1_index],cmap="YlGnBu",vmin=puntos[cat1_index].values.min(),vmax=puntos[cat1_index].values.max(),center=np.median(puntos[cat1_index].values), ax= self.ax)
        self.ax.collections[-1].colorbar.update_normal(self.ax)
        #this is a list of all images that have been plotted
        #self.ax.collections[-1].colorbar.set_clim(puntos[cat1_index].values.min(),puntos[cat1_index].values.max())
        self.ax.set_xticklabels(list(map(numDia.get, dias[cat1_index])))
        self.fig.canvas.draw_idle()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    win = MainWindow()
    sys.exit(app.exec_())

每次更新中都会添加颜色栏

1 个答案:

答案 0 :(得分:2)

每次调用sns.heatmap都会创建一个新的颜色栏。

您应该在init函数中创建用于色标的特定轴。我在这里使用GridSpec创建的轴比主轴薄10倍。还有许多其他方法可以创建此轴,只需在此处进行搜索即可。

def __init__(self):
    (...)
    self.fig = Figure()
    gs00 = matplotlib.gridspec.GridSpec(1, 2, width_ratios=[10,1])
    self.ax = self.fig.add_subplot(gs00[0])
    self.cax = self.fig.add_subplot(gs00[1])
    (...)

然后将对此对象的引用传递给sns.heatmap

def update(self):
    (...)
    sns.heatmap(..., ax=self.ax, cbar_ax=self.cax)
    (...)