[英]How do I stagger or offset x-axis labels in Matplotlib?
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. 您可以循环遍历x轴刻度线,并增加每隔一个刻度线的打击垫,使它们低于其他刻度线。 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. 您可以在轴标签中使用换行符(
\\n
)。 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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.