【问题标题】:How give different colors for different group of barplots in python?如何在python中为不同的条形图组赋予不同的颜色?
【发布时间】:2020-06-14 00:21:13
【问题描述】:

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

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)

输出

必填

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

类似链接

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

    这是使用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'])      
    

    【讨论】:

      【解决方案2】:

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

      提供:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-07
        • 2012-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-24
        • 2022-01-14
        • 1970-01-01
        相关资源
        最近更新 更多