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

gz5pxeao  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(140)

到目前为止,我有:

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.为什么它是紫色的,而不是实际的默认颜色和减少阿尔法。
1.如何为每种颜色添加图例。

wqnecbli

wqnecbli1#

这样做奏效了:

...
    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()

相关问题