【问题标题】:Change color of bar plot in Python在 Python 中更改条形图的颜色
【发布时间】:2017-08-15 20:03:26
【问题描述】:

我有三组按组显示的直方图。在此设置中,我想按颜色 区分每个组。

例如,隔间 - 红色,走廊 - 蓝色,办公室 - 绿色。有什么建议吗?

这是我当前的代码:

df_mean['mean'].hist(by=df_mean['type'])

【问题讨论】:

    标签: python pandas histogram


    【解决方案1】:

    您是否尝试过将颜色参数传递给 hist?

    plt.hist(x, color='r')
    

    【讨论】:

    • 是的,我试过了。但是,它并不区分每个标签。我希望每个组有不同的颜色。
    【解决方案2】:

    您可以在使用df.hist() 创建图形后为每个直方图设置颜色,如下例所示:

    import numpy as np                 # v 1.19.2
    import pandas as pd                # v 1.1.3
    import matplotlib.pyplot as plt    # v 3.3.2
    
    # Create random dataset
    rng = np.random.default_rng(seed=12345) # random number generator
    df = pd.DataFrame(dict(area_type = np.repeat(['cubicle', 'hallway', 'office'], [9, 10, 12]),
                           mean = np.append(rng.uniform(low=100, high=1400, size=9),
                                            rng.exponential(scale=500, size=22))))
    
    # Plot grid of histograms using pandas df.hist (note that df.plot.hist
    # does not produce the same result, it seems to ignore the 'by' parameter)
    grid = df['mean'].hist(by=df['area_type'])
    colors = ['red', 'blue', 'green']
    
    # Loop through axes contained in grid and list of colors
    for ax, color in zip(grid.flatten(), colors):
        # Loop through rectangle patches representing the histogram contained in ax
        for patch in ax.patches:
            patch.set_color(color)
    
    # Change size of figure
    plt.gcf().set_size_inches(8, 6)
    
    plt.show()
    

    除了手动选择颜色,您还可以从选定的colormap 中自动选择颜色(在这种情况下,定性颜色图是合适的),如下所示:

    # Select colormap properties
    cmap_name = 'Accent' # enter any colormap name (see whole list by running plt.colormaps())
    ncolors = df['area_type'].nunique()
    
    # Extract list of colors that span the entire gradient of the colormap
    cmap = plt.cm.get_cmap(cmap_name)
    colors = cmap(np.linspace(0, 1, ncolors))
    
    # Create plot like in previous example
    grid = df['mean'].hist(by=df['area_type'])
    for ax, color in zip(grid.flatten(), colors):
        for patch in ax.patches:
            patch.set_color(color)
    plt.gcf().set_size_inches(8, 6)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2011-08-03
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-06
      • 2021-07-16
      • 2012-10-18
      • 2013-12-11
      相关资源
      最近更新 更多