如何在子图中制作透明直方图?

问题描述 投票:0回答:1

到目前为止我已经:

def add_alpha_to_colormap(cmap, alpha):
    # borrowed from https://saturncloud.io/blog/adding-alpha-to-an-existing-matplotlib-colormap-a-guide/
    cmap = plt.cm.get_cmap(cmap)
    colors = cmap(np.arange(cmap.N))

    # Add alpha to the RGB array
    RGBA = np.hstack([colors[:, :3], np.full((cmap.N, 1), alpha)])

    # Create new colormap
    new_cmap = mcolors.ListedColormap(RGBA)

    return new_cmap


...

num_bins = 20
fig, axes = plt.subplots(figsize=(18, 14), dpi=120, nrows=2, ncols=4)
cmap = add_alpha_to_colormap('viridis', alpha=0.5)
for model in set(df.index):
    df.loc[model]['rouge1_recall'].plot.hist(cmap=cmap, bins=num_bins, title='Rouge1 recall', ax=axes[0, 0])
    df.loc[model]['rouge1_precision'].plot.hist(cmap=cmap, bins=num_bins, title='Rouge1 precision', ax=axes[1, 0])
    df.loc[model]['rouge2_recall'].plot.hist(cmap=cmap, bins=num_bins, title='Rouge2 recall', ax=axes[0, 1])
    df.loc[model]['rouge2_precision'].plot.hist(cmap=cmap, bins=num_bins, title='Rouge2 precision', ax=axes[1, 1])
    df.loc[model]['bert_recall'].plot.hist(cmap=cmap, bins=num_bins, title='BertScore recall', ax=axes[0, 2])
    df.loc[model]['bert_precision'].plot.hist(cmap=cmap, bins=num_bins, title='BertScore recall', ax=axes[1, 2])
    df.loc[model]['bleu'].plot.hist(cmap=cmap, bins=num_bins, title='Bleu', ax=axes[0, 3])
plt.show()

这给了我这个:

我不知道:

  1. 为什么它会变成紫色,而不是具有降低的 alpha 值的实际默认颜色。
  2. 如何为每种颜色添加图例。
python pandas matplotlib colors histogram
1个回答
0
投票

这有效:

    ...
    num_bins = 20
    fig, axes = plt.subplots(figsize=(18, 14), dpi=120, nrows=2, ncols=4)
    cmap = add_alpha_to_colormap('tab10', alpha=0.25)
    for c, model in enumerate(set(df.index)):
        model_label = ...
        df.loc[model]['rouge1_recall'].plot.hist(color=cmap.colors[c], bins=num_bins, title='Rouge1 recall', ax=axes[0, 0], label=model_label)
        df.loc[model]['rouge1_precision'].plot.hist(color=cmap.colors[c], bins=num_bins, title='Rouge1 precision', ax=axes[1, 0], label=model_label)
        df.loc[model]['rouge2_recall'].plot.hist(color=cmap.colors[c], bins=num_bins, title='Rouge2 recall', ax=axes[0, 1], label=model_label)
        df.loc[model]['rouge2_precision'].plot.hist(color=cmap.colors[c], bins=num_bins, title='Rouge2 precision', ax=axes[1, 1], label=model_label)
        df.loc[model]['bert_recall'].plot.hist(color=cmap.colors[c], bins=num_bins, title='BertScore recall', ax=axes[0, 2], label=model_label)
        df.loc[model]['bert_precision'].plot.hist(color=cmap.colors[c], bins=num_bins, title='BertScore recall', ax=axes[1, 2], label=model_label)
        df.loc[model]['bleu'].plot.hist(color=cmap.colors[c], bins=num_bins, title='Bleu', ax=axes[0, 3], label=model_label)
        # set legend
        for i in range(2):
            for j in range(4):
                axes[i, j].legend(loc="upper right")
    plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.