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

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

到目前为止,我有:

  1. def add_alpha_to_colormap(cmap, alpha):
  2. # borrowed from https://saturncloud.io/blog/adding-alpha-to-an-existing-matplotlib-colormap-a-guide/
  3. cmap = plt.cm.get_cmap(cmap)
  4. colors = cmap(np.arange(cmap.N))
  5. # Add alpha to the RGB array
  6. RGBA = np.hstack([colors[:, :3], np.full((cmap.N, 1), alpha)])
  7. # Create new colormap
  8. new_cmap = mcolors.ListedColormap(RGBA)
  9. return new_cmap
  10. ...
  11. num_bins = 20
  12. fig, axes = plt.subplots(figsize=(18, 14), dpi=120, nrows=2, ncols=4)
  13. cmap = add_alpha_to_colormap('viridis', alpha=0.5)
  14. for model in set(df.index):
  15. df.loc[model]['rouge1_recall'].plot.hist(cmap=cmap, bins=num_bins, title='Rouge1 recall', ax=axes[0, 0])
  16. df.loc[model]['rouge1_precision'].plot.hist(cmap=cmap, bins=num_bins, title='Rouge1 precision', ax=axes[1, 0])
  17. df.loc[model]['rouge2_recall'].plot.hist(cmap=cmap, bins=num_bins, title='Rouge2 recall', ax=axes[0, 1])
  18. df.loc[model]['rouge2_precision'].plot.hist(cmap=cmap, bins=num_bins, title='Rouge2 precision', ax=axes[1, 1])
  19. df.loc[model]['bert_recall'].plot.hist(cmap=cmap, bins=num_bins, title='BertScore recall', ax=axes[0, 2])
  20. df.loc[model]['bert_precision'].plot.hist(cmap=cmap, bins=num_bins, title='BertScore recall', ax=axes[1, 2])
  21. df.loc[model]['bleu'].plot.hist(cmap=cmap, bins=num_bins, title='Bleu', ax=axes[0, 3])
  22. plt.show()

这给了我这个:

我不知道
1.为什么它是紫色的,而不是实际的默认颜色和减少阿尔法。
1.如何为每种颜色添加图例。

wqnecbli

wqnecbli1#

这样做奏效了:

  1. ...
  2. num_bins = 20
  3. fig, axes = plt.subplots(figsize=(18, 14), dpi=120, nrows=2, ncols=4)
  4. cmap = add_alpha_to_colormap('tab10', alpha=0.25)
  5. for c, model in enumerate(set(df.index)):
  6. model_label = ...
  7. df.loc[model]['rouge1_recall'].plot.hist(color=cmap.colors[c], bins=num_bins, title='Rouge1 recall', ax=axes[0, 0], label=model_label)
  8. df.loc[model]['rouge1_precision'].plot.hist(color=cmap.colors[c], bins=num_bins, title='Rouge1 precision', ax=axes[1, 0], label=model_label)
  9. df.loc[model]['rouge2_recall'].plot.hist(color=cmap.colors[c], bins=num_bins, title='Rouge2 recall', ax=axes[0, 1], label=model_label)
  10. df.loc[model]['rouge2_precision'].plot.hist(color=cmap.colors[c], bins=num_bins, title='Rouge2 precision', ax=axes[1, 1], label=model_label)
  11. df.loc[model]['bert_recall'].plot.hist(color=cmap.colors[c], bins=num_bins, title='BertScore recall', ax=axes[0, 2], label=model_label)
  12. df.loc[model]['bert_precision'].plot.hist(color=cmap.colors[c], bins=num_bins, title='BertScore recall', ax=axes[1, 2], label=model_label)
  13. df.loc[model]['bleu'].plot.hist(color=cmap.colors[c], bins=num_bins, title='Bleu', ax=axes[0, 3], label=model_label)
  14. # set legend
  15. for i in range(2):
  16. for j in range(4):
  17. axes[i, j].legend(loc="upper right")
  18. plt.show()
展开查看全部

相关问题