3

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
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
user1507422
  • 369
  • 1
  • 4
  • 7

4 Answers4

3

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

After plt.savefig, add plt.close()

Community
  • 1
  • 1
mauve
  • 2,707
  • 1
  • 20
  • 34
1

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

Community
  • 1
  • 1
mdurant
  • 27,272
  • 5
  • 45
  • 74
1

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.

Community
  • 1
  • 1
pyan
  • 3,577
  • 4
  • 23
  • 36
0

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

cbar = fig.colorbar()
...
cbar.remove()
scrx2
  • 2,242
  • 1
  • 12
  • 17