python - 如何在 matplotlib 中移动刻度标签

标签 python matplotlib label

我想沿 x 轴水平移动一些刻度的标签,而不移动相应的刻度。

更具体地说,当使用 plt.setp 旋转标签时,标签文本的中心与刻度保持对齐。我想将这些标签向右移动,以便标签的近端对齐,如下图所示。

enter image description here

我知道this postthis one ,但是答案是有趣的拼凑,而不是问题的严格答案。

我的代码:

import matplotlib.pyplot as plt
import numpy as np
import datetime

# my fake data
dates = np.array([datetime.datetime(2000,1,1) + datetime.timedelta(days=i) for i in range(365*5)])
data = np.sin(np.arange(365*5)/365.0*2*np.pi - 0.25*np.pi) + np.random.rand(365*5) /3

# creates fig with 2 subplots
fig = plt.figure(figsize=(10.0, 6.0))
ax = plt.subplot2grid((2,1), (0, 0))
ax2 = plt.subplot2grid((2,1), (1, 0))
## plot dates
ax2.plot_date( dates, data )

# rotates labels 
plt.setp( ax2.xaxis.get_majorticklabels(), rotation=-45 ) 

# try to shift labels to the right
ax2.xaxis.get_majorticklabels()[2].set_y(-.1)
ax2.xaxis.get_majorticklabels()[2].set_x(10**99)

plt.show()

奇怪的是,set_y 的行为符合预期,但即使我将 x 设置为 fantasillion,标签也不会移动一毫。 (使用plot_date可能会带来额外的困惑,但同样的情况实际上也发生在plot上。)

最佳答案

首先,让我们使用 mcve 来展示问题。

import numpy as np
import datetime
import matplotlib.pyplot as plt
plt.rcParams["date.autoformatter.month"] = "%b %Y"

# my fake data
dates = np.array([datetime.datetime(2000,1,1) + datetime.timedelta(days=i) for i in range(365)])
data = np.sin(np.arange(365)/365.0*2*np.pi - 0.25*np.pi) + np.random.rand(365) /3

# creates fig with 2 subplots
fig, ax = plt.subplots(figsize=(6,2))
## plot dates
ax.plot_date( dates, data )

# rotates labels 
plt.setp( ax.xaxis.get_majorticklabels(), rotation=-45 ) 

plt.tight_layout()
plt.show()

enter image description here

现在正如其他答案已经指出的那样,您可以使用文本的水平对齐方式。

# rotates labels and aligns them horizontally to left 
plt.setp( ax.xaxis.get_majorticklabels(), rotation=-45, ha="left" )

enter image description here

您可以使用 rotation_mode 参数让旋转发生在文本的左上角,在这种情况下给出稍微更好的结果。

# rotates labels and aligns them horizontally to left 
plt.setp( ax.xaxis.get_majorticklabels(), rotation=-45, ha="left", rotation_mode="anchor") 

enter image description here

如果这些选项不够细粒度,即您想要更准确地定位标签,例如将其向一侧移动一些点,您可以使用变换。以下代码将使用 matplotlib.transforms.ScaledTranslation 将标签在水平方向上偏移 5 个点。

import matplotlib.transforms

plt.setp( ax.xaxis.get_majorticklabels(), rotation=-45) 

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

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

enter image description here

与例如相比,这样做的优点@explorerDude 提供的解决方案是偏移量独立于图中的数据,因此它通常适用于任何绘图,并且对于给定的字体大小看起来相同。

关于python - 如何在 matplotlib 中移动刻度标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59651231/

相关文章:

c++ - 如果达到结束条件,是否可以在 C++ 中退出 for before time?

python - 如何加快 mplot3d 的渲染速度?

python - matplotlib imshow 固定方面和垂直颜色条匹配主轴高度

html - 无法操作标签和字段 Bootstrap

python - XGBoost 错误 info.labels.size() != 0U (0 vs. 0)

Mac 10.8 上的 Python 2.7 pylab(无限运行)

python - 创建一个基于值 excel 填充的饼图?

python - Django ORM 分组依据

python - Python中链式赋值的现状

python - 打印不带括号的 numpy 数组