簡體   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