matplotlib在循环中绘图,删除colorbar但仍留有空格

时间:2014-08-01 18:12:25

标签: python 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 个答案:

答案 0 :(得分: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()

答案 1 :(得分:1)

我有一个非常类似的问题,我最终通过以类似的方式定义颜色条轴来解决这个问题: Multiple imshow-subplots, each with colorbar

与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)