繁体   English   中英

Why did matplotlib.figure.Figure object store the data from a following pandas.DataFrame.plot command?

[英]Why did matplotlib.figure.Figure object store the data from a following pandas.DataFrame.plot command?

新手来了在我迄今为止使用和学习的所有 Python 模块中,我发现 matplotlib 是最令人困惑的一个。 我相信这是因为存在两个接口:基于状态的基于 MATLAB Vs 面向对象。 在 class 中,我认为我们使用了基于状态的方法,而我发现面向对象的方法通常更合乎逻辑(并由 matplotlib 文档推荐)。

我正在使用我在下面的 jupyter 笔记本上发布的代码(代码是从这里提取的)。

import pandas as pd
import matplotlib.pyplot as plt

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

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)


fig, ax = plt.subplots()
ax.set_xlim([-10000, 140000])
ax.set_xlabel('Total Revenue')
ax.set_ylabel('Customer')
top_10.plot(kind='barh', y="Sales", x="Name", ax=ax)

我的问题如下:如果在前面的代码之后我只运行一个新块:

fig

它重印了整个 plot,包括来自 top_10 DataFrame 的数据。 DataFrame 的数据是如何成为我的object 的一部分的?

这是因为,pandas plot() function 固有地使用 matplotlib 的 plot() function。 并且在您的代码中使用fig, ax = plt.subplots()初始化了一个新的 plot。 所以,如果你想要一个新的 plot 你可以在top_10.plot(kind='barh', y="Sales", x="Name", ax=ax)之后使用fig, ax = plt.subplots() )

暂无
暂无

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

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