简体   繁体   中英

How do I stagger or offset x-axis labels in Matplotlib?

I was wondering if there is an easy way to offset x-axis labels in a way similar to the attached image.

在此处输入图片说明

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

在此处输入图片说明

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

在此处输入图片说明

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')

胶版标签示例

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM