【问题标题】:Running code line by line versus as a selection (in Ipython using Spyder)逐行运行代码与作为选择(在 Ipython 中使用 Spyder)
【发布时间】:2017-09-25 05:53:56
【问题描述】:

我正在慢慢地从 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 步:

选项 1,步骤 2

选项 2

我猜测结果在某种程度上“在引擎盖下”会是相同的,我尝试使用plt.showplt.drawfig.draw 渲染图表。但到目前为止还没有运气。

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

谢谢!

编辑:

我在 Windows 上使用 Spyder 2.3.8 和 Python 3.5.1

【问题讨论】:

    标签: python matplotlib ipython spyder


    【解决方案1】:

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

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

    plt.show() 在这里帮不上忙(别问我为什么没有实现)。

    但是,您可以随时简单地声明对图形的引用,fig 以获取图形的图像。

    【讨论】:

      猜你喜欢
      • 2017-12-03
      • 2018-07-26
      • 2017-10-25
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多