Matplotlib 中最后一张图上显示的所有热图颜色条

All heatmap colorbars displaying on last figure in Matplotlib

我在 Matplotlib 中绘制多个热图时遇到了问题(Python 3.6.0 以防万一)。

我有一个函数可以绘制一些数据的热图,每个热图都在一个单独的图中。当我 运行 这个函数用于不同的数据数组时,热图在各自的图形中都绘制得很好,但由于某种原因,它们的所有颜色条都显示在最近绘制的热图的图形上,如链接的图像所示下面。

热图错误

请注意,当我尝试在没有该功能的情况下手动绘制热图时,此行为仍然存在。另请注意,颜色条不仅显示在最近绘制的图形上,而且仅显示在最近绘制的包含热图 的图形 上。例如,如果我稍后绘制一个折线图,颜色条不会显示在此折线图上,而只会显示在最后一个热图上。

这是一个最小的工作示例:

import numpy as np
from pylab import *

# Function
f1 = lambda X, Y: X*X + Y*Y
f2 = lambda X, Y: X*X - Y*Y
f3 = lambda X, Y: X*Y - Y

# Grid on which function is to be evaluated
x = np.arange(0, 100, 1)
y = np.arange(0, 100, 1)
Xaxis = x[:, None]
Yaxis = y[None, :]

# Evaluate functions and create labels for plotting
Z1 = f1(Xaxis, Yaxis)
l1 = ['F1', '1']
Z2 = f2(Xaxis, Yaxis)
l2 = ['F2', '2']
Z3 = f3(Xaxis, Yaxis)
l3 = ['F3', '3']


# Function to plot heatmaps
def DoPlot(fig, fun, label):
    title = label[0]
    subscript = label[1]
    ax = fig.add_subplot(111)
    im = ax.imshow(fun, cmap=cm.viridis, interpolation='nearest', 
                   aspect='auto')
    ax.set_ylabel('Y')
    ax.set_xlabel('X')
    cbar = colorbar(im)
    cbar.set_label(r'$Z_{{}}$'.format(subscript))
    fig.suptitle(title)
    fig.tight_layout()


# Plot the heatmaps

fig1 = figure()
fig2 = figure()
fig3 = figure()

DoPlot(fig1, Z1, l1)
DoPlot(fig2, Z2, l2)
DoPlot(fig3, Z3, l3)

show()

(是的,我确实意识到 from pylab import * 不是最佳实践。这只是为了方便。)

非常感谢在此问题上的任何帮助。

这里的技巧是直接对对象进行操作。因此,请使用 fig.colorbar.

而不是 colorbar

正如您在问题中提到的那样 from pylab import * 强烈建议不要使用。将您的代码升级到面向对象的接口是微不足道的:

import numpy as np
from matplotlib import pyplot

# Function
f1 = lambda X, Y: X*X + Y*Y
f2 = lambda X, Y: X*X - Y*Y
f3 = lambda X, Y: X*Y - Y

# Grid on which function is to be evaluated
x = np.arange(0, 100, 1)
y = np.arange(0, 100, 1)
Xaxis = x[:, None]
Yaxis = y[None, :]

# Evaluate functions and create labels for plotting
Z1 = f1(Xaxis, Yaxis)
l1 = ['F1', '1']
Z2 = f2(Xaxis, Yaxis)
l2 = ['F2', '2']
Z3 = f3(Xaxis, Yaxis)
l3 = ['F3', '3']


# Function to plot heatmaps
def DoPlot(fig, fun, label):
    title = label[0]
    subscript = label[1]
    ax = fig.add_subplot(111)
    im = ax.imshow(fun, cmap=pyplot.cm.viridis, interpolation='nearest', 
                   aspect='auto')
    ax.set_ylabel('Y')
    ax.set_xlabel('X')
    cbar = fig.colorbar(im)  # change: use fig.colorbar
    cbar.set_label(r'$Z_{{}}$'.format(subscript))
    fig.suptitle(title)
    fig.tight_layout()


# Plot the heatmaps
## change: use the pyplot function
fig1 = pyplot.figure()
fig2 = pyplot.figure()
fig3 = pyplot.figure()

DoPlot(fig1, Z1, l1)
DoPlot(fig2, Z2, l2)
DoPlot(fig3, Z3, l3)

pyplot.show()  ## change

您也可以使用简单的 for 循环来减少代码重复,但这超出了本题的范围。