循环中绘制matplotlib,移除色条但空白仍然存在
我的代码大概是这样的:
更新:我重新写了一些实际的示例代码,反映了我遇到的主要问题。另外,我意识到颜色条的创建是在实际循环中进行的,不然就没有东西可以映射了。之前的代码有点匆忙,工作日结束时急着写的,抱歉。
import numpy
import matplotlib as mplot
import matplotlib.pyplot as plt
import os
#make some mock data
x = np.linspace(1,2, 100)
X, Y = np.meshgrid(x, x)
Z = plt.mlab.bivariate_normal(X,Y,1,1,0,0)
fig = plt.figure()
ax = plt.axes()
'''
Do some figure-related stuff that take up a lot of time,
I want to avoid having to do them in the loop over and over again.
They hinge on the presence of fig so I can't make
new figure to save each time or something, I'd have to do
them all over again.
'''
for i in range(1,1000):
plotted = plt.plot(X,Y,Z)
cbar = plt.colorbar(ax=ax, orientation = 'horizontal')
plt.savefig(os.path.expanduser(os.path.join('~/', str(i))))
plt.draw()
mplot.figure.Figure.delaxes(fig, fig.axes[1]) #deletes but whitespace remains
'''
Here I need something to remove the colorbar otherwise
I end up with +1 colorbar on my plot at every iteration.
I've tried various things to remove it BUT it keeps adding whitespace instead
so doesn't actually fix anything.
'''
有没有人遇到过这个问题并成功解决了?希望这些信息能让你大致了解我的问题,如果需要的话我可以提供更多代码,但我觉得给个概述示例会更简洁一些。
谢谢。
2 个回答
1
我遇到了一个非常相似的问题,最后通过定义一个颜色条的坐标轴解决了这个问题,做法和这里的链接很像:多个imshow子图,每个都有颜色条
相比mdurant的回答,这种方法的好处是不用手动定义坐标轴的位置。
import matplotlib.pyplot as plt
import IPython.display as display
from mpl_toolkits.axes_grid1 import make_axes_locatable
from pylab import *
%matplotlib inline
def plot_res(ax,cax):
plotted=ax.imshow(rand(10, 10))
cbar=plt.colorbar(mappable=plotted,cax=cax)
fig, axarr = plt.subplots(2, 2)
cax1 = make_axes_locatable(axarr[0,0]).append_axes("right", size="10%", pad=0.05)
cax2 = make_axes_locatable(axarr[0,1]).append_axes("right", size="10%", pad=0.05)
cax3 = make_axes_locatable(axarr[1,0]).append_axes("right", size="10%", pad=0.05)
cax4 = make_axes_locatable(axarr[1,1]).append_axes("right", size="10%", pad=0.05)
# plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0.3, hspace=0.3)
N=10
for j in range(N):
plot_res(axarr[0,0],cax1)
plot_res(axarr[0,1],cax2)
plot_res(axarr[1,0],cax3)
plot_res(axarr[1,1],cax4)
display.clear_output(wait=True)
display.display(plt.gcf())
display.clear_output(wait=True)
2
colorbar()
这个函数让你可以明确指定要在哪个坐标轴上显示颜色条。这样做的好处是,你可以确保颜色条总是在同一个位置出现,不会占用其他坐标轴的空间。此外,你还可以重设一个已经存在的颜色条的 .mappable
属性,而不是每次都重新定义它。
下面是一个关于明确指定坐标轴的例子:
x = np.linspace(1,2, 100)
X, Y = np.meshgrid(x, x)
Z = plt.mlab.bivariate_normal(X,Y,1,1,0,0)
fig = plt.figure()
ax1 = fig.add_axes([0.1,0.1,0.8,0.7])
ax2 = fig.add_axes([0.1,0.85,0.8,0.05])
...
for i in range(1,5):
plotted = ax1.pcolor(X,Y,Z)
cbar = plt.colorbar(mappable=plotted, cax=ax2, orientation = 'horizontal')
#note "cax" instead of "ax"
plt.savefig(os.path.expanduser(os.path.join('~/', str(i))))
plt.draw()