在Matplotlib中绘制多个热图时,我遇到了一个问题(Python3.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 *
不是最佳实践。这只是为了方便。)
在这件事上的任何帮助都是非常感谢的。
发布于 2018-01-11 19:01:56
这里的诀窍是直接对对象进行操作。所以,不要使用colorbar
,而是使用fig.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
循环来减少代码的重复性,但这超出了这个问题的范围。
https://stackoverflow.com/questions/48213443
复制相似问题