首页 > 解决方案 > 即使 figursize 发生变化,如何修复图例的位置?

问题描述

我想创建一些与下图非常相似的图表。

import matplotlib.pyplot as plt
import numpy as np


labels = ['2015', '2016', '2017', '2018', '2019']
group_a = [20, 34, 30, 35, 27]
group_b = [25, 32, 34, 20, 25]
group_c = [10, 14, 10, 20, 17]
group_d = [16, 4, 8, 15, 18]

x = np.arange(len(labels))
width = 0.2

fig, ax = plt.subplots(figsize=(14, 7))

ax.bar(x - width/2, group_a, width, label='Group 1')
ax.bar(x + width/2, group_b, width, label='Group 2')
ax.bar(x + width/2 +width, group_c, width, label='Group 3')
ax.bar(x - width/2 -width, group_d, width, label='Group 4')

ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend(loc='upper left',
          bbox_to_anchor=(0.075, -0.075),
          fancybox=True,
          ncol=2,
          fontsize=8,
          frameon=False)
ax.annotate('Categorie 1\nCategorie 2',
            xy=(0, 0),
            xytext=(0, -55),
            linespacing=1.7,
            Fontsize=8,
            textcoords='axes points')

fig.tight_layout()

plt.show()

图片1

这些数字非常好,但是随着数字大小的变化,我很难定位图例和注释。使用 figsize (7,2) 图例向上和向右移动,而注释保持在同一位置: 图二

问题: 即使 figursize 发生变化,如何修复图例的位置?对于图例,我没有找到类似于使用 textcoords=“axes points”的解决方案,它可以确保无论图形大小如何,注释都保持在同一位置。

我还没有找到传说的任何解决方案。我想知道以下是否可行,或者是否还有其他我还没有想到的解决方案

任何想法如何解决这个问题?提前感谢您的帮助!

问候

标签: pythonmatplotlibpositionlegendfigure

解决方案


推荐阅读