python 运行选中的代码,逐行运行代码与选择运行(在使用Spyder的Ipython中)

I'm slowly transitioning from R to Python, and some of the more subtle differences are driving me a bit nuts. I found a really interesting guide on Effectively Using Matplotlib in the blog Practical Business Python

Here, the author shows how to build a chart step by step using the following lines of code (short version):

# 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)

I'm messing around with this in Spyder, and I've noticed that there is a difference betweene running parts of this code line by line versus running the same lines as a selection.

Option 1, step 1:

1tf4T.png

Option 1, step 2

b167aa1ef439a909234c3b683eed48af.png

Option 2

50b01c7dedc6b377da83cabf505b9039.png

I was guessing that the result somehow would be the same "under the hood", and I've tried rendering the chart using plt.show, plt.draw and fig.draw. But no luck so far.

I assume that the answer to this has got something to do with very basic functionality in IPython and / or how these elements are assigned to memory, but the whole thing just leaves me confused. I'm hoping some of you find the time to explaing this, and perhaps offer further suggestions on how to wrestle with these things.

Thanks!

Edit:

I'm using Spyder 2.3.8 with Python 3.5.1 on Windows

解决方案

In the IPython console within Spyder, the figure will be shown if a figure object is detected in the cell.

Because the fig, ax = plt.subplots() has a figure object in it, the (empty) figure is shown.

If afterwards a plotting command on the axes is effectuated, no figure object is detected, so only the return of the cell is shown as text.

plt.show() will not help here (don't ask me why it hasn't been implemented).

However, you can at any point simply state the reference to the figure, fig to obtain the image of the figure.

cbe1b2c23d768ee9c4e8cc2679cd9538.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值