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