【发布时间】:2021-12-06 23:34:46
【问题描述】:
我正在尝试打印子图中的顶级项目,但使用我使用的代码,我得到了双打印轴 我怎样才能防止这种情况发生 感谢您的帮助
您可以在下面看到代码和结果图
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
Cat = ['A', 'B', 'C']
It = ['D', 'E', 'F','G','H','I','J']
n=365
df = pd.DataFrame({'Category': np.random.choice(Cat, n ),
'Item': np.random.choice(It, n ),
'Net sales':np.random.randint(100,500,(n)),
'Date':np.random.choice( pd.date_range('1/1/2021', periods=365,
freq='D'), n, replace=False)})
# Grouping products by sales
prod_sales = pd.DataFrame(df.groupby('Item').sum()['Net sales'])
# Sorting the dataframe in descending order
prod_sales.sort_values(by=['Net sales'], inplace=True, ascending=False)
# fig, ax = plt.subplots(figsize=(20,10))
fig, ax = plt.subplots(5,2,figsize=(20,10))
i=0
for section, group in df.groupby('Item'):
if any(item in section for item in prod_sales[:4].index):
i=i+1
ax = fig.add_subplot(2, 2, i)
group.plot(x='Date', y='Net sales', ax=ax, label=section)
【问题讨论】:
-
预期输出是什么?
-
您添加 10 个子图,然后再创建 4 个。您添加的 10 个子图位于 4 个新子图之下。
-
试试这个:
fig, axs = plt.subplots(4,2,figsize=(20,10));fig.subplots_adjust(hspace = 0.5, wspace=0.1);axs = axs.ravel();for ax, (section, group) in zip(axs, df.groupby('Item')): group.plot(x='Date', y='Net sales', ax=ax, label=section) -
@r-beginners 感谢它可以绘制所有内容。我知道如何弄清楚如何只绘制前 n 个“项目”,因为我的原始数据有很多项目。再次感谢
-
@CutePoison 每个前 n 个项目的子图(我的原始数据有很多项目)
标签: python pandas dataframe matplotlib jupyter-notebook