Skip to content Skip to sidebar Skip to footer

Dividing Long Xticks In 2 Lines Matplotlib

I have the following matplotlib I would like to divide x-ticks into 2 lines instead of 1 because sometimes they are so long that is why they come over another and then it is imposs

Solution 1:

You can use re as suggested on this answer and create a list of new labels with a new line character after every 10th character.

import re
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

xlabels = ["to Schleswig-Holstein", "to Mecklenburg-Vorpommern", r"to Lower Saxony"]

xlabels_new = [re.sub("(.{10})", "\\1\n", label, 0, re.DOTALL) for label in xlabels]

plt.plot(range(3))
plt.xticks(range(3), xlabels_new)
plt.show()

enter image description here

Alternative

xlabels_new = [label.replace('-', '-\n') for label in xlabels]

enter image description here

Post a Comment for "Dividing Long Xticks In 2 Lines Matplotlib"