python - 如何偏移 x 轴刻度以使其他刻度稍低/略高?

标签 python matplotlib plot figure

我的绘图上的次要 x 轴标签非常密集。我不想让它们变得更小,而是想稍微向下移动所有其他的,以便它们适合轴。类似于 this 。我试过label padding但没有成功。

enter image description here

代码:

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

最佳答案

我认为你犯了一个根本性错误。您应该在字符串之前附加新行字符,因为只有这样您才会在下面一行看到标签文本。否则,您只是将光标发送到下一行而不打印任何内容。

此外,您需要label.get_text()来获取刻度标签的字符串。我在下面展示了一个示例答案。将相同的逻辑应用于您的示例。我不能这样做,因为你没有提供 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()

enter image description here

关于python - 如何偏移 x 轴刻度以使其他刻度稍低/略高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56469593/

相关文章:

python - 向 matplotlib 颜色图图例添加垂直标签

python - 使用 FuncAnimation 动态更新 3d 散点图/点图中的 ax.text 位置

python - 求和导数

python - Apache 导入错误 : No module named _socket in wsgi deployment on Django

python - 在 Python 中按所有项目的数字排序列表

r - 如何重新投影诸如 "wrld_simpl"之类的 map ?

r - 绘制具有多个参数的曲线

python - pymc3 中具有(大)时间^2 项的分层模型中的 MCMC 收敛

Pandas 条形图更改日期格式

r - 将带有指数的数字转换为 R 中美丽图例的绘图命令