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

随声附和 提交于 2021-02-19 01:24:55

问题


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


回答1:


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




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/51898101/how-do-i-stagger-or-offset-x-axis-labels-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!