【问题标题】:How to plot bar graph for top five game for each genre using for loop如何使用for循环为每种类型的前五名游戏绘制条形图
【发布时间】:2021-05-14 20:12:51
【问题描述】:
genre_game=group_game.groupby(["Genre","Name"])"Global_Sales"].sum().reset_index().sort_values(["Genre","Global_Sales"],ascending=(True,False))

       
genre_game

enter image description here

genre_s=df["Genre"].unique()
genre_sorted=sorted(genre_s)
print(f'List of : {genre_sorted}' )

列表:['Action', 'Adventure', 'Fighting', 'Misc', 'Platform', 'Puzzle', 'Racing', 'Role-Playing', 'Shooter', 'Simulation', '体育”、“策略”]

def f(genre):
    for genre  in genre_sorted:
        
        
        plt.bar(genre_game[genre][:5],genre_game["Global_Sales"][genre:genre+5])
        plt.xticks(rotation=90)
        
        
f("Adventure")

【问题讨论】:

  • 请不要将数据/代码/错误消息作为图片发布。在 SO 上直接在此处发布文本。
  • 会记住这一点

标签: python pandas dataframe matplotlib data-analysis


【解决方案1】:

你可以在没有循环的情况下做到这一点。此示例按前 2 大销售额分组,但您可以将 2 更改为 5 或任何数字。

import pandas as pd
import matplotlib.pyplot as plt

genre = ['Action', 'Action', 'Action', 'Strategy', 'Strategy', 'Strategy']
name =['GTAV', 'GTAIV', 'FIFA13', 'Worms2', 'Tropico', 'WarOverworld']
sales = [55, 13, 16, 1, 1, 0.5]
df = pd.DataFrame(list(zip(genre, name, sales)), 
                  columns=['genre', 'name', 'sales'])

df2 = df.groupby('genre') \
                 .apply(lambda x: x.nlargest(2, 'sales')) \
                 .reset_index(drop=True) 

plt.bar(df2.name, df2.sales)
plt.xlabel('x')
plt.ylabel('% global')
plt.show()

下面是源 df 的样子:

以下是前 2 个df2 的样子:

【讨论】:

  • 我真的很喜欢你处理数据框分组方法的方式,但我仍然没有回答为特定类型绘制条形图而不使用 if else 的问题。
  • def f(genre): if Genre=="Action": plt.bar(df2.Name[:5], df2.Global_Sales[:5]) elif Genre=="Adventure": plt.bar(df2.Name[5:10], df2.Global_Sales[:5])
  • 我不想在每个循环中都使用 if esle,你能帮我解决这个问题吗
  • @RishabhGupta,请用(1)更好的示例数据集修改您的问题; (2)您预期输出的示例; (3) 说明您的问题,包括您为什么想要或不想使用循环或 if/then 条件。对于 (1),您可以从我的示例中看到在您的问题中包含数据框是多么容易。如果你给出了一个很好的示例数据集,那么为(2)画一张图应该很容易。对于 (3),您的 cmets 令人困惑,因为您说您想在一个评论中使用 if/then 并说您不想在另一条评论中使用它。当您解决这些问题时,我们可以为您提供帮助。
猜你喜欢
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
相关资源
最近更新 更多