逐行运行代码作为选择(在使用Spyder的Ipython中)

问题描述 投票:0回答:1

我正在慢慢地从R转换到Python,而一些更微妙的差异让我有点疯狂。我在博客Practical Business Python上找到了一篇关于有效使用Matplotlib的有趣指南

在这里,作者展示了如何使用以下代码行(简短版本)逐步构建图表:

# Modules
import pandas as pd
import matplotlib.pyplot as plt

# Get the data
df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true")
df.head()

# Rearrange data
top_10 = (df.groupby('name')['ext price', 'quantity'].agg({'ext price': 'sum', 'quantity': 'count'})
      .sort_values(by='ext price', ascending=False))[:10].reset_index()
top_10.rename(columns={'name': 'Name', 'ext price': 'Sales', 'quantity': 'Purchases'}, inplace=True)

# Customize plot
plt.style.use('ggplot')

# And here's the part that puzzles me:
fig, ax = plt.subplots()
top_10.plot(kind='barh', y="Sales", x="Name", ax=ax)

我在Spyder中搞砸了这个,我注意到这个代码逐行运行部分与运行与选择相同的行之间存在差异。

选项1,第1步:

enter image description here

选项1,第2步

enter image description here

选项2

enter image description here

我猜测结果会以某种方式“引擎盖下”,并且我尝试使用plt.showplt.drawfig.draw渲染图表。但到目前为止没有运气。

我认为这个问题的答案与IPython中的基本功能有关,和/或这些元素如何分配给内存,但整件事让我感到困惑。我希望你们中的一些人能够找到解释这个问题的时间,也许还会就如何解决这些问题提出进一步的建议。

谢谢!

编辑:

我在Windows上使用Spyder 2.3.8和Python 3.5.1

python matplotlib ipython spyder
1个回答
2
投票

在Spyder的IPython控制台中,如果在单元格中检测到图形对象,则会显示该图。 因为fig, ax = plt.subplots()中有一个数字对象,所以显示了(空)数字。

如果之后在轴上执行绘图命令,则不会检测到图形对象,因此只有单元格的返回显示为文本。

plt.show()在这里不会帮忙(不要问我为什么没有实施)。

但是,您可以在任何时候简单地声明对图形的引用,fig以获得图形的图像。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.