0

I need to plot two sets of barplots side by side with their values on two separate y-axis.

In the example code below, my population bar is in different scale with income. It's not working with just one axis.

Here is what I need:

  1. I need plot three bars for income of each region. Also I need three population bars right next to each of the income bar.
  2. Because they are in different scale, I will need dual y axis.
  3. Values on top of each bar.
import matplotlib.pyplot as plt
import seaborn as sns

data = pd.DataFrame({'region': ['A', 'B', 'C'],
        'population': [1000, 2000, 30000],
        'income': [40, 50, 60]})
data = pd.melt(data, id_vars=['region'], var_name='metric', value_name='value')

sns.barplot(data=data, x='region', y= 'value', hue='metric')
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
zesla
  • 11,155
  • 16
  • 82
  • 147
  • 1
    Perhaps see [this question](https://stackoverflow.com/questions/27019153/how-to-scale-seaborns-y-axis-with-a-bar-plot) which might be helpful. – SanguineL May 16 '23 at 15:22
  • how do I put values on top of those bars? – zesla May 16 '23 at 18:49
  • In terms of data presentation, this `data.plot(kind='bar', x='region', secondary_y='income', rot=0)` is not a good plot because, while there are two axes, visually having bars that are 60 and 30000 be the same length is misleading. Additionally, I don't see a way to extract the right `axes` in order to add a bar label. The better option is to use `log` scale on the y-axis. With the melted `data`: `ax = sns.barplot(data=data, x='region', y= 'value', hue='metric', log=True)` or with the first data: `ax = data.plot(kind='bar', x='region', rot=0, logy=True)`. – Trenton McKinney May 16 '23 at 20:14
  • For either option, use `for c in ax.containers: ax.bar_label(c, label_type='edge')` to add labels. – Trenton McKinney May 16 '23 at 20:15
  • See [code and plot](https://i.stack.imgur.com/fckWv.png) – Trenton McKinney May 16 '23 at 20:18

0 Answers0