Based on the following example from matplotlib, I have made a function that plots two weekly time series as a side-by-side bar chart. https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py
My problem is that I set the xticks explicitly, and that creates messy xtick-labels. Is there a way to get matplotlib to choose xticks (position and labels) explicitly in such a plot?
I must say that I find the whole operation with specifycing the position of the bar using (x - width/2) quite inelegant to get side-by-side-bars - are there other options (other packages than matplotlib or other specifications in matplotlib) to avoid writing such explicit code?
Below is code and result. I'm seeking a solution that selects the number and placements of xticks and xticklabels that leaves it readable:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
labels = ['W1-2020', 'W2-2020', 'W3-2020', 'W4-2020', 'W5-2020','W6-2020','W7-2020','W8-2020','W9-2020','W10-2020','W11-2020','W12-2020','W13-2020','W14-2020','W15-2020']
men_means = [20, 34, 30, 35, 27,18,23,29,27,29,38,28,17,28,23]
women_means = [25, 32, 34, 20, 25,27,18,23,29,27,29,38,19,20, 34]
x = np.arange(len(labels)) # the label locations
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, men_means, width, label='Men')
rects2 = ax.bar(x + width/2, women_means, width, label='Women')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
fig.tight_layout()
plt.show()