Reputation: 301
I was wondering if there is an easy way to offset x-axis labels in a way similar to the attached image.
Upvotes: 9
Views: 12585
Reputation: 869
You can use newline characters (\n
) in your axis labels. You just need to put your labels in a list of strings, and add a newline to every other one. Here is a minimum working example
import matplotlib as mpl
import matplotlib.pyplot as plt
xdata = [0,1,2,3,4,5]
ydata = [1,3,2,4,3,5]
xticklabels = ['first label', 'second label', 'third label', 'fourth label', 'fifth label', 'sixth label']
f,ax = plt.subplots(1,2)
ax[0].plot(xdata,ydata)
ax[0].set_xticks(xdata)
ax[0].set_xticklabels(xticklabels)
ax[0].set_title('ugly overlapping labels')
newxticklabels = [l if not i%2 else '\n'+l for i,l in enumerate(xticklabels)]
ax[1].plot(xdata,ydata)
ax[1].set_xticks(xdata)
ax[1].set_xticklabels(newxticklabels)
ax[1].set_title('nice offset labels')
Upvotes: -1
Reputation: 339350
You may include a linebreak for every second label.
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(42)
x = ["".join(np.random.choice(list("ABCDEF"), 3)) for i in range(10)]
y = np.cumsum(np.random.randn(10))
fig, ax = plt.subplots(figsize=(3.5,3))
ax.plot(x,y)
ax.set_xticklabels(["\n"*(i%2) + l for i,l in enumerate(x)])
fig.tight_layout()
plt.show()
Upvotes: 3
Reputation: 25371
You can loop through your x axis ticks and increase the pad for every other tick so that they are lower than the other ticks. A minimal example would be:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3,4,5])
ax.set_xticks([1,2,3,4,5])
ax.set_xticklabels(["A","B","C","D","E",])
# [1::2] means start from the second element in the list and get every other element
for tick in ax.xaxis.get_major_ticks()[1::2]:
tick.set_pad(15)
plt.show()
Upvotes: 16