简体   繁体   English

为什么 '%matplotlib inline' 在 python 脚本中不起作用?

[英]Why doesn't '%matplotlib inline' work in python script?

The following does not work:以下不起作用:

在此处输入图片说明

However this totally works in Jupiter Notebook.然而,这完全适用于 Jupiter Notebook。

在此处输入图片说明

If I simply comment it out, the graph doesn't show up.如果我只是将其注释掉,则图表不会显示。 (Maybe it won't show up anyways) (也许无论如何它都不会出现)

import pandas as pd
import matplotlib

from numpy.random import randn
import numpy as np

import matplotlib.pyplot as plt

df = pd.read_csv('data/playgolf.csv', delimiter='|' )
print(df.head())

hs = df.hist(['Temperature','Humidity'], bins=5)
print(hs)

Other answers and comments have sufficiently detailed why %matplotlib inline cannot work in python scripts.其他答案和评论已经足够详细地说明了为什么%matplotlib inline不能在 python 脚本中工作。

To solve the actual problem, which is to show the plot in a script, the answer is to use要解决实际问题,即在脚本中显示情节,答案是使用

plt.show()

at the end of the script.在脚本的末尾。

If you are using notebook and run my_file.py file as a module如果您使用 notebook 并将 my_file.py 文件作为模块运行

Change the line "%matplotlib inline" to "get_ipython().run_line_magic('matplotlib', 'inline')".将行“%matplotlib inline”更改为“get_ipython().run_line_magic('matplotlib', 'inline')”。 Then run my_file.py using this %run It should look like this:然后使用这个 %run 运行 my_file.py 它应该是这样的:

In my_file.py:在 my_file.py 中:

get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('matplotlib', 'inline')

In notebook:在笔记本中:

%run my_file.py % 运行 my_file.py

This run my_file.py in ipython, which help avoid the bug这在 ipython 中运行 my_file.py,这有助于避免错误

NameError: name 'get_ipython' is not defined NameError:未定义名称“get_ipython”

According tohttp://ipython.readthedocs.io/en/stable/interactive/magics.html , % is a special iPython/Jupyter command:根据http://ipython.readthedocs.io/en/stable/interactive/magics.html%是一个特殊的 iPython/Jupyter 命令:

Define an alias for a system command.为系统命令定义别名。

%alias alias_name cmd defines alias_name as an alias for cmd %alias alias_name cmd定义alias_name作为cmd的别名

In standard Python, % takes the remainder when one number is divided by another (or can be used for string interpolation), so in a standard Python program, %matplotlib inline doesn't make any sense.在标准 Python 中, %在一个数除以另一个数时取余数(或可用于字符串插值),因此在标准 Python 程序中, %matplotlib inline没有任何意义。 It does, however, work in iPython, as described above.然而,它确实可以在 iPython 中工作,如上所述。

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

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