3

I am trying to plot group of bar charts. I was able to give different colors within each group but how to give different colors to different groups?

MWE

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



df = pd.DataFrame({0: [10,20,80],
                  1: [20,40,60]},index=['a','b','c'])

df

# another test dataframe
df = pd.DataFrame({0: [10,20,80,10],
                  1: [20,40,60,70],
                  2: [20,40,60,70],
                  },
                  index=['a','b','c','d'])

pal = 'magma'
color=sns.color_palette(pal,len(df)) # list of rgb

fig, ax = plt.subplots()

df.plot.bar(ax=ax,color=color)

Output

enter image description here

Required

Here the variable color has three values, I want to use these three colors for three groups. For example group a now has two colors, I want it to have only one color.

Similar links

BhishanPoudel
  • 15,974
  • 21
  • 108
  • 169

2 Answers2

1

Here is a workaround using plt.bar()

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



df = pd.DataFrame({0: [10,20,80],
                  1: [20,40,60],
                  'g':['a','b','c']})

pal = 'magma'
color=sns.color_palette(pal,len(df)) # list of rgb

fig, ax = plt.subplots()


width=.25

gb = df.groupby('g')
positions = range(len(gb))

for c, x, (_, group) in zip(color, positions, gb):

    ax.bar(x-width/2, group[0], width, color=c, edgecolor='k')
    ax.bar(x+width/2, group[1], width, color=c, edgecolor='k')

ax.set_xticks(positions)
ax.set_xticklabels(df['g'])      

enter image description here

warped
  • 8,947
  • 3
  • 22
  • 49
1

You can use axis.patches:

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


df = pd.DataFrame({0: [10,20,80,10],
                  1: [20,40,60,70],
                  2: [20,40,60,70],
                  },
                  index=['a','b','c','d'])

pal = 'magma'
color = sns.color_palette(pal,len(df)) # list of rgb
color = color * df.shape[1]


fig, ax = plt.subplots()

df.plot.bar(ax=ax)
ax.get_legend().remove()

for p,c in zip(ax.patches,color):
    p.set_color(c)

Gives: enter image description here

BhishanPoudel
  • 15,974
  • 21
  • 108
  • 169