繁体   English   中英

python SyntaxError: 无效的语法 %matplotlib inline

[英]python SyntaxError: invalid syntax %matplotlib inline

我在我的 python 脚本中遇到了这个错误:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

from utils import progress_bar_downloader
import os
#Hosting files on my dropbox since downloading from google code is painful
#Original project hosting is here: https://code.google.com/p/hmm-speech-recognition/downloads/list
#Audio is included in the zip file
link = 'https://dl.dropboxusercontent.com/u/15378192/audio.tar.gz'
dlname = 'audio.tar.gz'

if not os.path.exists('./%s' % dlname):
    progress_bar_downloader(link, dlname)
    os.system('tar xzf %s' % dlname)
else:
    print('%s already downloaded!' % dlname)

我想使用 matplotlib 但它给出了语法错误,我试过 sudo apt-get install python-matplotlib

如果您没有使用 Jupyter IPython notebook,只需注释(或删除)该行,一切都会正常工作,并且如果您从控制台运行 Python 脚本,则会打开一个单独的绘图窗口。

但是,如果您使用的是 Jupyter IPython notebook,则 notebook 中的第一个 python 代码单元应该有一行“%matplotlib inline”,以便您能够查看任何绘图。

"%matplotlib inline" 不是有效的 python 代码,所以你不能把它放在脚本中。

我假设您使用的是 Jupyter 笔记本? 如果是这样,把它放在第一个单元格中,一切都应该工作。

"%matplotlib inline" 是一个神奇的命令,最适合 Jupyter IPython notebook。 此命令使图像在使用 Jupyter notebook 时自动显示在浏览器中,而无需调用 show()。 IPython 是支持这些神奇命令的核心,但在这种情况下,仅从控制台使用 IPython 是不够的,因为此特定调用试图内联显示图形。 不确定它是否适用于任何其他组合,但首先,使用 Jupyter notebook。

您只能在单元格内使用此代码。 按 Shift+Enter 执行它。

In []: %matplotlib inline

由于这不是有效的 python 代码,如果我们将它包含在 python 脚本中,它将返回语法错误(即使脚本是使用导入或其他机制从 Jupyter notebook 执行的)。

与任何其他快捷方式一样,如果不想使用 jupyter notebook,您可以从 Python 脚本中删除“%matplotlib inline”并在末尾添加 show() 以显示您的绘图。

在 Spyder 中内联使用%matplotlib时,我遇到了相同的语法错误。
在我用以下代码行替换它之后,我想成功绘制的系列new_obj显示在控制台上:

    import matplotlib.pyplot as plt
    new_obj.resample('M').sum().plot(kind="bar")
    plt.show()

%matplotlib inline 仅在 Ipython 控制台中运行良好,否则它在 Jupyter Notebook 中非常有效且频繁地运行。 因此,在我的建议中,如果您想使用 Matplotlib,那么请使用 Jupyter Notebook

评论 [ %matplotlib 内联 ]

添加 [ plt.show() ]

简单有效的代码:

import pandas_datareader.data as web
import datetime
import matplotlib.pyplot as plt
# %matplotlib inline

start = datetime.datetime(2012,1,1)
end = datetime.datetime(2017,1,1)

tesla = web.DataReader('TSLA','yahoo',start,end)
tesla['Open'].plot()
plt.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM