如何在python中为不同的条形图组指定不同的颜色?

如何在python中为不同的条形图组指定不同的颜色?,python,pandas,matplotlib,seaborn,Python,Pandas,Matplotlib,Seaborn,我正在尝试绘制一组条形图。我可以在每组中给不同的颜色,但是如何给不同的组赋予不同的颜色呢 MWE 输出 要求的 这里变量color有三个值,我想将这三种颜色用于三个组。例如,组a现在有两种颜色,我希望它只有一种颜色 类似链接 这里有一个使用plt.bar()的变通方法。 您可以使用axis.patches: import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt

我正在尝试绘制一组条形图。我可以在每组中给不同的颜色,但是如何给不同的组赋予不同的颜色呢

MWE 输出

要求的 这里变量
color
有三个值,我想将这三种颜色用于三个组。例如,组
a
现在有两种颜色,我希望它只有一种颜色

类似链接

这里有一个使用
plt.bar()的变通方法。


您可以使用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)

给出:

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'])      
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)