2

I am trying to plot countries departments and their sales. So i have country, departments and their sales numbers in diff columns. And i need to create bar plot, so it should look like country1 and its departments on x-axis and sales y-axis, then country2 and so-on.

I tried seaborn's catplot but its giving me a diff plot for each country, using plotly's bar its just plotting all the departments together. I need it to be grouped based on the countries.

Any input is appreciated. Thanks

Chetan
  • 31
  • 3
  • 4
    Can you provide a sample of your data? – PieCot Jan 29 '21 at 22:23
  • 1
    You have to share a little piece of your code if you want people to share with you a little bit of their knowledge. – swiss_knight Jan 29 '21 at 22:26
  • 1
    I am sharing the example: Main_Sector Country Count 0 Others USA 2923 1 Cleantech / Semiconductors USA 2297 2 Social, Finance, Analytics, Advertising USA 1912 0 Others GBR 143 1 Cleantech / Semiconductors GBR 127 2 Social, Finance, Analytics, Advertising GBR 98 0 Others IND 109 1 News, Search and Messaging IND 52 2 Entertainment IND 33 – Chetan Jan 29 '21 at 22:34

1 Answers1

1

You could create a barplot() using 'Country' as x and 'Department' as hue:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns

df = pd.DataFrame({'Country': np.repeat(['Albania', 'Botswana', 'Chili'], 4),
                   'Department': np.tile(['Department1', 'Department2', 'Department3', 'Department4'], 3),
                   'Sales': np.random.randint(10000, 100000, 12)})
sns.barplot(data=df, x='Country', y='Sales', hue='Department')
plt.show()

example plot

An approach to cope with empty bars, is to create stacked bars:

df.pivot(index='Country', columns='Department').plot(kind='bar', stacked=True, rot=0)

stacked bars example

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • 1
    This is pretty much what i was looking for. But, let's say there are some departments missing in some of the countries.Example: US finance 100 US sales 200 US HR 300 UK finance 250 UK transport 80 UK manufacturing 130 So, now its creating blanks in UK for sales and HR. Is there a way to tackle it – Chetan Jan 29 '21 at 22:43
  • 1
    In that case the bar for that department will be empty. – JohanC Jan 29 '21 at 22:45
  • 1
    Can i remove those blank bars? – Chetan Jan 29 '21 at 22:48
  • 1
    I updated the answer with stacked bars, which don't have a problem with empty bars. Otherwise, [How to add group labels for bar charts in matplotlib?](https://stackoverflow.com/questions/19184484/how-to-add-group-labels-for-bar-charts-in-matplotlib) might be worth looking at. In general, I don't think there is a clear solution. – JohanC Jan 29 '21 at 23:23
  • Thanks JohanC, The link you shared is very good. I am trying to get the solution from that. Much appreciated – Chetan Jan 29 '21 at 23:36