0

I have a pandas DataFrame tha looks like this:

import pandas as pd

temp = pd.DataFrame({'country':['A1','A1','A1','A1','A2','A2','A2','A2'],
                     'seg':    ['S1','S2','S1','S2','S1','S2','S1','S2'],
                     'agegroup':    ['1', '2', '2', '1','1', '2', '2', '1'],
                      'N' : [21,22,23,24,31,32,33,34]})

and i create the following plot:

sns.factorplot(data=temp, x='seg', y='N', hue='agegroup', row='country', kind='bar',
                   orient='v', legend=True, aspect=1)

I would like to do the following :

1. rotate it 45 degrees, so that the bars are horizontally and not vertically. I tried this sns.factorplot(data=temp, x='seg', y='N', hue='agegroup', row='country', kind='bar', orient='h', legend=True, aspect=1)

but i get the following error TypeError: unsupported operand type(s) for /: 'str' and 'int'

2. Have the numbers N on top of each bar. I tried to follow this but i couldn't make it work

Isma
  • 14,604
  • 5
  • 37
  • 51
quant
  • 4,062
  • 5
  • 29
  • 70

1 Answers1

1

You changed the orientation of the plot but kept the same x, y parameters, you need to swap them as follows:

plot = sns.factorplot(data=temp, y='seg', x='N', hue='agegroup', row='country', kind='bar',
               orient='h', legend=True, aspect=1)

Then the graph will be rendered horizontally.

Edit

To display the labels on top of the bars, this is the closest I could get, hopefully it will get you going:

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

temp = pd.DataFrame({'country':['A1','A1','A1','A1','A2','A2','A2','A2'],
                     'seg':    ['S1','S2','S1','S2','S1','S2','S1','S2'],
                     'agegroup':    ['1', '2', '2', '1','1', '2', '2', '1'],
                      'N' : [21,22,23,24,31,32,33,34]})

plot = sns.factorplot(data=temp, y='seg', x='N', hue='agegroup', row='country', kind='bar',
                   orient='h', legend=True, aspect=1)

ax = plt.gca()

for p in ax.patches:
    ax.text(p.get_width(), p.get_y() + p.get_height()/2., '%d' % int(p.get_width()), 
            fontsize=12, color='red', ha='right', va='center')
Isma
  • 14,604
  • 5
  • 37
  • 51