pandas 图未显示 [英] Pandas plot doesn't show
问题描述
在脚本(不是IPython)中使用它时,什么也没有发生,即绘图窗口不出现:
When using this in a script (not IPython), nothing happens, i.e. the plot window doesn't appear :
import numpy as np
import pandas as pd
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.plot()
即使添加time.sleep(5)
,也仍然没有任何内容.为什么?
Even when adding time.sleep(5)
, there is still nothing. Why?
有没有办法做到,无需手动调用matplotlib ?
推荐答案
绘制完成后,您需要告诉matplotlib show
完成它.通常的处理方式是导入matplotlib.pyplot
并从那里调用show
:
Once you have made your plot, you need to tell matplotlib to show
it. The usual way to do things is to import matplotlib.pyplot
and call show
from there:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.plot()
plt.show()
由于您已请求不这样做(为什么?),因此可以使用以下[注意:这似乎不再适用于pandas
的较新版本]:
Since you have requested not to do that (why?), you could use the following [NOTE: This no longer appears to work with newer versions of pandas
]:
import numpy as np
import pandas as pd
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts.plot()
pd.tseries.plotting.pylab.show()
但是您在这里所做的所有事情都是在pandas
中导入了matplotlib
的地方,然后从那里调用相同的show
函数.
But all you are doing there is finding somewhere that matplotlib
has been imported in pandas
, and calling the same show
function from there.
您是否要避免为了提高速度而致电matplotlib
?如果是这样,那么您实际上并没有加快速度,因为pandas
已经导入了pyplot
:
Are you trying to avoid calling matplotlib
in an effort to speed things up? If so then you are really not speeding anything up, since pandas
already imports pyplot
:
python -mtimeit -s 'import pandas as pd'
100000000 loops, best of 3: 0.0122 usec per loop
python -mtimeit -s 'import pandas as pd; import matplotlib.pyplot as plt'
100000000 loops, best of 3: 0.0125 usec per loop
最后,您在评论中链接的示例的原因不需要调用matplotlib
是因为它是在iPython notebook
中而不是在脚本中交互式运行的.
Finally, the reason the example you linked in comments doesn't need the call to matplotlib
is because it is being run interactively in an iPython notebook
, not in a script.
这篇关于 pandas 图未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!