Consider the following plot, where we plot the same data into panel A with vertical labels and into panel B with horizontal labels using text wrapping.
import matplotlib.pyplot as plt
x = "Very long label"
y = "Even much longer label"
z = "Now this is what I call a really long label"
l = [x, y, z]
d = [3, 1, 4]
fig, (axA, axB) = plt.subplots(1, 2, figsize=(10, 5))
axA.bar(l, d)
font_dictA={"va": "center", "ha": "right", "rotation": 90, "wrap": True}
axA.set_xticklabels(l, fontdict= font_dictA)
axA.set_title("Case A: vertical labels")
axB.bar(l, d)
font_dictB={"va": "top", "ha": "center", "rotation": 0, "wrap": True}
axB.set_xticklabels(l, fontdict= font_dictB)
axB.set_title("Case B: horizontal labels")
plt.subplots_adjust(bottom=0.2)
plt.show()
giving the following output:
I assume that text wrapping does not work for horizontal labels is caused by differences in the bounding box calculation which is determined by taking the axis and border into consideration (vertical labels), but not adjacent label text boxes (horizontal labels). Can we easily set the text box dimensions of the labels for the horizontal labels (think: define their max-width)?
Please note that I only want to wrap the text of labels/legends/text with matplotlib functionality; I do not ask for external libraries like textwrap nor for other solutions like rotating labels.