Search code examples
pythonmatplotliblegendcolorbar

How to remove legend from an image plot


I am trying to remove the legend of the spectrogram (I am trying to get a 244x244 pixel image)

I have tried Remove the legend on a matplotlib figure but it works in a very weird way - I get the result and an exception!

colab exception and the result I want

(I am using google colab)

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import moviepy.editor as mpy

import youtube_dl
## downloading the video
ydl_opts = {
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'wav',
        'preferredquality': '192',
    }],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=5pIpVK3Gecg'])

## selecting the audio clip from 17oth second to 180th second and saving it in talk.wav
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
ffmpeg_extract_subclip("Tyler, The Creator - 'IGOR,' Odd Future and Scoring a" 
                       "Number 1 Album _ Apple Music-5pIpVK3Gecg.wav", 170, 
                       180, targetname="talk.wav")


talk = mpy.AudioFileClip('talk.wav')
# switching axis off
plt.axis('off')

sample_rate = talk.fps
NFFT = sample_rate /25
audio_data = talk.to_soundarray()
#trying to get a 244 x 244 pixel image 
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(2.44, 2.44), dpi=100.)

ax.axis('off')

spectrum, freqs, time, im = ax.specgram(audio_data.mean(axis=1), NFFT=NFFT, pad_to=4096, 
                                        Fs=sample_rate, noverlap=512, mode='magnitude', )


########## the problem lies here ##########
ax.get_legend.remove()

##trying to save stuff to drive but this doesnt run because of the exception
fig.colorbar(im)
fig.savefig('specto.png')

import os
print( os.getcwd() )
print( os.listdir('specto.png') )

from google.colab import files
files.download( "specto.png" ) 

Is there a way to fix this?


Solution

  • ax.get_legend refers to the function object itself, ax.get_legend() (note parentheses) calls the function and returns a matplotlib.legend.Legend instance or None. The syntax should be

    ax.get_legend().remove()
    

    However, if no legend has been added to the plot this will raise

    AttributeError: NoneType object has no attribute remove

    so it is best to guard it with a try and except clause unless you know ahead of time that there will be a legend.


    Edit

    Based on the comment, you are confusing matplot.pyplot.colorbar() with matplotlib.pyplot.legend(), hence why it "appears to work" when an exception is raised before the line

    fig.colorbar(img)
    

    It simply never draws the colorbar because it doesn't reach that line. If you don't want a colorbar then remove the lines

    ax.get_legend().remove()
    
    fig.colorbar(im)
    

    and you will get a spectrogram without a colorbar.