为 Python 中的多直方图网格图的每个条添加独特的颜色

Adding unique colors for each bar of a multi-histogram grid plot in Python

我正在尝试使用 Matplotlib 在 Python 中创建一个多直方图,每个 class ( bar ) 都有一个独特的颜色。

我能够绘制图表,但无法使条形图的颜色正常工作。这是我的代码:

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

def draw_histograms(df, variables, n_rows, n_cols):
    fig=plt.figure() # facecolor='g' changes the background color
    for i, var_name in enumerate(variables):
        ax=fig.add_subplot(n_rows,n_cols,i+1)
        df[var_name].hist(ax=ax)

    fig.tight_layout()
    fig.set_size_inches(20.5, 10.5)
    plt.show()

draw_histograms(df_final, df_final.columns, 2, 3)

这看起来像什么:

将“facecolor”添加到 plt.figure(),更改背景颜色。

我的数据框:

我想要实现的目标:对于 DF 中的每一列,我显示一个图表(总共 6 个)。每个直方图中的 3 个条形图描绘了情绪 - 正面、负面和中性。我想用 3 种独特的颜色来描绘所有 6 个图表中的不同情绪。

您正在绘制直方图,而您只有 3 个值,为每个值创建一个高度为 1 的条形(或者当 2 个值非常接近时,高度为 2)。将其绘制为条形图会更清楚,这确实允许每个条形使用一种颜色。为了使事情具有可比性,在所有子图中设置相同的 x 限制可能很有用:

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

def draw_histograms(df, variables, n_rows, n_cols, bar_width=1, xmin=0, xmax=None):
    fig = plt.figure(figsize=(20.5, 10.5))
    for i, var_name in enumerate(variables):
        ax = fig.add_subplot(n_rows, n_cols, i + 1)
        # df[var_name].plot.bar(ax=ax, color=['crimson', 'gold', 'limegreen'], rot=0)
        ax.bar(x=df[var_name], height=1, width=bar_width, color=['crimson', 'gold', 'limegreen'])
        ax.set_xlim(xmin, xmax + bar_width)
        for spine in ['right', 'top']:
            ax.spines[spine].set_visible(False)
    fig.tight_layout()
    plt.show()

df = pd.DataFrame([[1186, 181, 1960, 955, 2263, 2633],
                   [664, 171, 463, 723, 381, 697],
                   [570, 152, 336, 544, 269, 492]],
                  index=['negative', 'neutral', 'positve'])
bar_width = 30
xmax = df.max().max()
draw_histograms(df, df.columns, 2, 3, bar_width=bar_width, xmax=xmax)

def draw_histograms(df, variables, n_rows, n_cols, ymin=0, ymax=None):
    fig = plt.figure(figsize=(20.5, 10.5))
    for i, var_name in enumerate(variables):
        ax = fig.add_subplot(n_rows, n_cols, i + 1)
        df[var_name].plot.bar(ax=ax, color=['crimson', 'gold', 'limegreen'], rot=0)
        ax.set_ylim(ymin, ymax)
        ax.bar_label(ax.containers[0], size=16)
        for spine in ['right', 'top']:
            ax.spines[spine].set_visible(False)
    fig.tight_layout()
    plt.show()

ymax = df.max().max()
draw_histograms(df, df.columns, 2, 3, ymax=ymax * 1.1)

同样的信息也可以使用显示值的条形高度和使用 x 值显示名称来显示。