简体   繁体   English

如何使用 matplotlib 将主要和次要刻度标签精确对齐

[英]How to align major and minor tick labels exactly next to each other with matplotlib

I have a graph with major tick labels the first day of months, and minor tick labels the other days of the month.我有一个图表,其中包含月份的第一天的主要刻度标签,以及月份的其他日子的次要刻度标签。 If you look closely you can see that the day strings are not aligned.如果仔细观察,您会发现日期字符串未对齐。 I would like to move minor labels a little bit down to align them with majors.我想将次要标签向下移动一点,以使它们与专业对齐。 or vice versa.或相反亦然。

I don't want to make minor ticks bigger, or majors smaller我不想让小刻度变大,或者让大刻度变小

How would I do that?我该怎么做?

This is the code piece, to generate the major/minor labels like in figure:这是代码片段,用于生成如图所示的主要/次要标签:

# draw canvas for x-ticks/labels
fig.canvas.draw()

# x-axis ticks/labels
x_minor_labels = [item for item in ax.xaxis.get_minorticklabels()]
for item in x_minor_labels:
    if int(item.get_text()) in (8, 15, 22, 29):
        item.set_visible(True)
    else:
        item.set_visible(False)

x_major_labels = [item for item in ax.xaxis.get_majorticklabels()]
x_major_labels[0].set_text(x_major_labels[0].get_text() + str(2021))
ax.set_xticks(ax.get_xticks().tolist())
ax.set_xticklabels(x_major_labels)

>>>x_minor_labels[0].get_position()
(18629.0, 0)
>>>x_major_labels[0].get_position()
(18628.0, 0)

在此处输入图像描述

Expected Outcome:预期结果:

在此处输入图像描述

Labels are just text objects, so you can just set a new position with the set_position method.标签只是文本对象,因此您可以使用 set_position 方法设置一个新的set_position

major_labels = ax.xaxis.get_majorxticklabels()
_, y = major_labels[0].get_position()

for label in ax.xaxis.get_minorxticklabels():
     x, _ = label.get_position()
     label.set_position(x, y)

fig.canvas.draw()

I found out I can move minor labels via:我发现我可以通过以下方式移动次要标签:

ax.get_xaxis().set_tick_params(which='minor', pad=5)

However, I am not sure setting pad=5 makes minor labels exactly next to major labels for all plots (for my case it works).但是,我不确定设置pad=5是否会使所有地块的主要标签紧挨着次要标签(就我而言,它有效)。 Probably also depends on the figure size etc... So an eleganter solution should exist.可能还取决于图形大小等......所以应该存在一个更优雅的解决方案。

在此处输入图像描述

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

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