简体   繁体   English

如何偏移x轴刻度线,使彼此之间略低/较高?

[英]How can I offset the x-axis ticks so every other is slightly lower/higher?

The minor x-axis labels on my plot are very dense. 我的绘图上的次要x轴标签非常密集。 Instead of making them smaller, I want to move every other one slightly down so they fit within the axis. 我不想让它们变小,而是希望彼此向下稍微移动,以使其适合轴内。 Something like this . 这样的东西。 I tried label padding but no success. 我尝试了标签填充,但没有成功。

在此处输入图片说明

Code: 码:

fig, ax1 = plt.subplots(figsize=(18, 6))

ax1.plot(data['date_time'], data.Casual, color='g')
ax1.plot(data['date_time'], data.Registered, color='b')

ax1.set(xlabel='', ylabel='Total # of trips started')
ax1.yaxis.label.set_size(13)
ax1.xaxis.set(
    major_locator=mdates.DayLocator(),
    major_formatter=mdates.DateFormatter('\n\n%A'),
    minor_locator=mdates.HourLocator(byhour=range(0,24,1)),
    minor_formatter=mdates.DateFormatter('%-H'),
)
ax1.tick_params(axis='x', which='minor', bottom=True)
ax1.set_xbound(data['date_time'][0],data['date_time'][166])
ax1.yaxis.set_ticks(np.arange(0, 550, 50))
ax1.set_ybound(0,550)
ax1.yaxis.grid(True, which='major')
ax1.xaxis.grid(True, which='major', color='green')

#borders
ax1.spines['left'].set_color('0.0')
ax1.spines['right'].set_color('0.0')
ax1.spines['bottom'].set_color('0.0')

# Create offset transform by 74 points in x direction
dx = 74/72.; dy = 0/72. 
offset = mpl.transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)

# apply offset transform to all x ticklabels.
for label in ax1.xaxis.get_majorticklabels():
    label.set_transform(label.get_transform() + offset)

### Trying to move them up and down here ###
labels_formatted = [label if i%2==0 else label+'\n' for i, label in enumerate(ax1.xaxis.get_majorticklabels())]
ax1.set_xticklabels(labels_formatted)


plt.show()

You are doing one fundamental mistake I think. 我认为您犯了一个基本错误。 You should append the new line character before the string because only then you will see the label text one line below. 您应该在字符串之前添加换行符,因为只有这样,您才会在下面一行看到标签文本。 Otherwise, you are just sending the cursor to the next line without printing anything. 否则,您只是将光标发送到下一行而不打印任何内容。

Moreover, you need label.get_text() to get the string of the tick-labels. 此外,您需要label.get_text()来获取刻度标签的字符串。 I am showing a sample answer below. 我在下面显示一个示例答案。 Adapt the same logic to your example. 将相同的逻辑应用于您的示例。 I cannot do that because you haven't provided a MCVE 我无法这样做,因为您尚未提供MCVE

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

x = np.linspace(0, 10, 20)

plt.plot(x, x**2)
fig.canvas.draw()
labels_formatted = [label.get_text() if i%2==0 else '\n'+label.get_text() for i, label in enumerate(ax.xaxis.get_majorticklabels())]
ax.set_xticklabels(labels_formatted)
plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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