【问题标题】:How to get rid of the double printed axis in matpotlib subplot如何摆脱 matplotlib 子图中的双打印轴
【发布时间】: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


【解决方案1】:

这是我的解决方案,不是最整洁的,很多行,但可以完成工作。可以进一步改进或缩短:

Tot = df['Item'].nunique() # number of sublots
Cols = 3 # number of columns in the subplot

Rows = Tot // Cols 
Rows += Tot % Cols
Position = range(1,Tot + 1)

# Create main figure
df = df.sort_values('Date')
fig = plt.figure(1, figsize = (20, 8))
for k, item in zip(range(Tot), df['Item'].unique()):
    ax = fig.add_subplot(Rows, Cols, Position[k])
    ax.set_title(item)
    ax.plot(df[df['Item'] == item]['Date'], df[df['Item'] == item]['Net sales'])

plt.show()

【讨论】:

  • 感谢这摆脱了双重打印,但现在它正在打印所有项目。我只想打印前 n 个,因为它是我原始数据中的一长串项目。感谢您的帮助
【解决方案2】:

我处理了上面的输入并使用了下面的代码 根据我的真实数据,它对我有用 谢谢大家的意见

df=concatenated_df.groupby('Category').resample('M', label='right',closed='left'
                                           , on='Date').sum().reset_index().sort_values(by='Date')

top_cat=df.groupby(['Category']).sum()['Net sales'].nlargest(30)

n=10
fig, axs = plt.subplots(round(n/2),2,figsize=(20,n*2));
fig.subplots_adjust(hspace = 0.5, wspace=0.1);
axs = axs.ravel();

# for ax, (section, group) in zip(axs, df.groupby('Category')):    
for ax, (section, group) in zip(axs, df[df.Category.isin(top_cat[:n].index)].groupby('Category')):    
    group.plot(x='Date', y='Net sales', ax=ax, label=section)
    ax.set_title(section )
    ax.set_ylim([0, 120000])

【讨论】:

  • 顺便说一下,我使用了 concatenated_df,因为它来自多个文件
猜你喜欢
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
  • 2018-01-15
  • 2014-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多