1

I would like to create quite some charts that are very similar to the figure below.

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

Picture 1

The figures are perfectly fine but I struggle positioning the legend and an annotation as the figuresize varies. Using figsize (7,2) the legend moves up and right while the annotation stays at the same position: Picture 2

Question: How can I fix the position of the legend even when figursize changes? For the legend I did not find a solution similar to the use of textcoords=“axes points”, which makes sure the annotation remains at the same position regardless of the size of the figure.

I did not find any solution for the legend yet. I was wondering if the following would work or if there other solutions I did not think of yet

  • Using ax.legend() trying to set a fix point in relation with the command ax.annotate()

  • Using a new command with similar arguments like annotate (“axes points”)

  • Using new classes like artist(), remove() and so on, that offer the same results like the command legend()

Any ideas how to solve this? Thanks in advance for any help!

Regards

tituszban
  • 4,797
  • 2
  • 19
  • 30
Walter
  • 11
  • 2
  • With something like 'axes points' you risk that the text is outside the figure. Are you always saving using the `savefig(..., bbox_inches="tight")` method? – ImportanceOfBeingErnest Sep 24 '19 at 16:54
  • If you want to make sure the legend or text is always inside the figure, check [this solution](https://stackoverflow.com/questions/42994338/creating-figure-with-exact-size-and-no-padding-and-legend-outside-the-axes/43001737#43001737). – ImportanceOfBeingErnest Sep 24 '19 at 17:08
  • I have already tried this. Importent is to fix the legend outside of the figure and in the exact same position like picture 1. – Walter Sep 25 '19 at 18:43

0 Answers0