如何从图像绘图中删除图例

3

我正在尝试移除频谱图的图例(我想要一个244x244像素的图像)

我已经尝试过在matplotlib图中移除图例,但它的效果非常奇怪 - 我得到了结果一个异常!

colab exception and the result I want

(我正在使用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" ) 

有什么方法可以解决这个问题吗?

1个回答

4

ax.get_legend 指的是函数对象本身,ax.get_legend()(注意括号)调用该函数并返回一个 matplotlib.legend.Legend 实例或 None。语法应该为

ax.get_legend().remove()

然而,如果没有将图例添加到图中,这将引发AttributeError: NoneType对象没有remove属性的错误。因此,最好使用try和except语句进行保护,除非您事先知道会有一个图例。

编辑

根据评论,您将matplot.pyplot.colorbar()matplotlib.pyplot.legend()混淆,因此在该行之前引发异常时,“似乎起作用”。

fig.colorbar(img)

它之所以不绘制色条,是因为它没有达到那一行。如果您不想要一个色条,那么请删除这些行。
ax.get_legend().remove()

fig.colorbar(im)

你将得到一张没有颜色条的频谱图。


我添加了括号,得到了正确的结果但出现了AttributeError。频谱图似乎总是有一个图例 - https://imgur.com/a/U3tfGlL 但当我执行ax.get_legend().remove()时,它似乎能够工作但会出现错误 - https://imgur.com/a/Ss4NFki 有没有一种方法可以在不出现错误的情况下使其正常工作? - Pradyumna

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接