Search code examples
pythonpandasmatplotlibbar-chartnormalize

How can I normalize data and create a stacked bar chart?


I have a data frame containing total sales of each game genre in 3 regions. I would it to create a stacked bar chart so that I can make a comparison of the sales of each genre across each region.

I know that I should normalize the data first, but have no idea how to.

I am very new to programming, so I would appreciate it if someone can provide a simple explanation on how I can go about doing this!!

This is my dataframe

regional_genre = video_sales_df.groupby(['Genre'],as_index=False)["NA_Sales","EU_Sales","JP_Sales"].sum()[:5]

Dataframe:

Genre       NA_Sales   EU_Sales   JP_Sales
Action      877,83     525        159,95
Adventure   105,8      64,13      52,07
Fighting    223,59     101,32     87,35
Misc        410,24     215,98     107,76
Platform    447,05     201,63     130,77

I used [:5] because I only want to plot the top 5 genres in each region.


Solution

  • This is probably something that you are trying to achieve. You can use sklearn for normalization and see below how to create a stacked bar plot. Use the normalization scale that you want.

    import pandas as pd
    from sklearn import preprocessing
    import matplotlib.pyplot as plt
    
    
    # Read data
    video_sales_df = pd.read_excel("data.xlsx")
    
    regional_genre = video_sales_df.groupby(['Genre'],as_index=False)["NA_Sales","EU_Sales","JP_Sales"].sum()[:5]
    columns = ["NA_Sales","EU_Sales","JP_Sales"]
    
    # Normalization parameters
    normalize_min = 0.1
    normalize_max = 1
    
    # Normalize
    regional_genre[columns]= preprocessing.minmax_scale(regional_genre[columns], feature_range=(normalize_min, normalize_max))
    
    # Plot stacked bars
    plt.bar(regional_genre["Genre"], regional_genre["NA_Sales"], label="NA_Sales")
    plt.bar(regional_genre["Genre"], regional_genre["EU_Sales"], bottom=regional_genre["NA_Sales"], label="EU_Sales")
    plt.bar(regional_genre["Genre"], regional_genre["JP_Sales"], bottom=regional_genre["EU_Sales"]+regional_genre["NA_Sales"], label="JP_Sales")
    plt.legend()
    plt.ylabel("Normalized sales")
    plt.show()
    
    
    

    result2

    Another solution:

    # Plot stacked bars
    plt.bar(columns, regional_genre.ix[0,1:], label="Action")
    bot = regional_genre.ix[0,1:]
    plt.bar(columns, regional_genre.ix[1,1:], bottom=bot, label="Adventure")
    bot += regional_genre.ix[1,1:]
    plt.bar(columns, regional_genre.ix[2,1:], bottom=bot, label="Fighting")
    bot += regional_genre.ix[2,1:]
    plt.bar(columns, regional_genre.ix[3,1:], bottom=bot, label="Misc")
    bot += regional_genre.ix[3,1:]
    plt.bar(columns, regional_genre.ix[4,1:], bottom=bot, label="Platform")
    plt.show()
    

    result2