user1507422
user1507422

Reputation: 369

remove colorbars from plot

I wrote some code to create a png of a raster object (self[:] = a np array). it's supposed to be a method, to easily make a plot Problem with the code is that it runs fine the first time, but when i run this method multiple times i get a picture with multiple legends.

enter image description here

I tried to get rid of it with delaxes, but this legend is really stubborn.
Any Idea's how to solve this are welcome

Here's the code:

    def plot(self,image_out,dpi=150, rotate = 60):
        xur = self.xur()
        xll = self.xll()
        yur = self.yur()
        yll = self.yll()
        fig = plt.figure()
    #tmp = range(len(fig.axes))
    #tmp = tmp[::-1]
    #for x in tmp:
    #    fig.delaxes(fig.axes[x])
        ax = fig.add_subplot(111)
        cax = ax.imshow(self[:],cmap='jet', extent = [yll,yur,xll,xur],
                            interpolation = 'nearest')
        cbar = fig.colorbar()
        plt.xticks(rotation=70)
        plt.tight_layout(pad = 0.25)
        plt.savefig(image_out,dpi=dpi)
        return

Upvotes: 3

Views: 11593

Answers (4)

scrx2
scrx2

Reputation: 2282

You can remove the colorbar by its .remove() method:

cbar = fig.colorbar()
...
cbar.remove()

Upvotes: 1

pyan
pyan

Reputation: 3707

I encountered the same problem and the answers in another post solved it

remove colorbar from figure in matplotlib

Please refer to the second answer

I had a similar problem and played around a little bit. I came up with two solutions which might be slightly more elegant:

Clear the whole figure and add the subplot (+colorbar if wanted) again.

If there's always a colorbar, you can simply update the axes with autoscale which also updates the colorbar.

I've tried this with imshow, but I guess it works similar for other plotting methods.

In particular, I used the first approach, which is to clear the figure by clf() and then re-add the axis each time.

Upvotes: 2

mdurant
mdurant

Reputation: 28673

A better option is to specify to colorbar which axes you would like to see it render into, see the example here.

Upvotes: 2

mauve
mauve

Reputation: 2763

You need to close the plot. I had this same problem

After plt.savefig, add plt.close()

Upvotes: 4

Related Questions