【问题标题】:Can't add colorbar to heatmap on a canvas using matplotlib无法使用 matplotlib 将颜色条添加到画布上的热图
【发布时间】:2020-08-15 07:02:00
【问题描述】:

我正在尝试将颜色条添加到我在 GUI 中绘制的图形中,但是当代码在没有颜色条代码行的情况下工作时,当我尝试添加颜色条时,我收到一条错误消息“AxesSubplot ' 对象没有属性 'get_array'。我试图找到一个解决方案,但我无法弄清楚我做错了什么。任何帮助将不胜感激。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
import tkinter as tk

a = np.array([2,-3,4,-2,1,2,4,3,5])
a = a.reshape(3,3)

class Graph:
    #Draws and return a placeholder for a graph
    #@param parent is the Tk.Frame parent obj
    #@param title is the (string) title for the graph
    def __init__(self, parent, title=''):
        #Initialise graph
        self.title = title
        self.fig = Figure(figsize=(4,4))
        self.plot = self.fig.add_subplot()
        self.plot.set_title(self.title)
        self.plot.set_ylim(top=1)
        self.plot.set_xlim(right=255)
        self.plot.set_ylabel("Certainty")
        self.plot.set_xlabel("Pixel Value")

        #Draw
        self.canvas = FigureCanvasTkAgg(self.fig, master=parent)
        self.canvas.get_tk_widget().pack()
        self.canvas.draw()

        return

    def plotMaxDistHeat(self, maxDistMatrix):
        #Clear previous plot
        self.plot.clear()

        #Plot new results
        self.plot.set_title(self.title)

        self.plot.imshow(maxDistMatrix, cmap='coolwarm')
        self.fig.colorbar(self.plot)

        #Draw Graph
        self.canvas.draw()

root = tk.Tk()

canvas = tk.Canvas(bg='red')
canvas.pack()
graph = Graph(canvas, title='Test Graph')

graph.plotMaxDistHeat(a)

tk.mainloop()

【问题讨论】:

  • Colorbar 需要您着色的对象,而不是轴对象。 IE。做 pc=imshow() 和 colorbar(pc)
  • @JodyKlymak 这应该是一个答案,而不是评论
  • @JodyKlymak 不是我做的吗?
  • pc = self.plot.imshow(maxDistMatrix, cmap='coolwarm'); self.fig.colorbar(pc, ax=self.plot)
  • @DizietAsahi 不确定是否有理由从只是误读文档的内容中得出完整的答案...

标签: python matplotlib tkinter plot heatmap


【解决方案1】:

替换

self.fig.colorbar(self.plot)

self.fig.colorbar(self.plot.imshow(maxDistMatrix, cmap='coolwarm'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2022-07-05
    • 2020-04-03
    • 1970-01-01
    相关资源
    最近更新 更多