我想沿x轴水平移动一些刻度线的标签,而不移动相应的刻度线。
更具体地说,当使用旋转标签时plt.setp
,标签文本的中心与刻度线保持对齐。我想将这些标签向右移动,以使标签的近端对齐,而不是如下图所示。
我知道这篇文章和这一个,但答案很有意思组装机,而不是严格的问题的答案。
我的代码:
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
为幻想,标签也不会移动一个iota。(使用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()
现在,正如其他答案所指出的那样,您可以使用文本的水平对齐方式。
# rotates labels and aligns them horizontally to left
plt.setp( ax.xaxis.get_majorticklabels(), rotation=-45, ha="left" )
您可以使用rotation_mode
参数使旋转在文本的左上角发生,在这种情况下,结果会更好一些。
# rotates labels and aligns them horizontally to left
plt.setp( ax.xaxis.get_majorticklabels(), rotation=-45, ha="left", rotation_mode="anchor")
如果这些选项的粒度不够细,即您想更准确地定位标签,例如将标签向侧面移动一些点,则可以使用变换。以下代码将使用a在水平方向上将标签偏移5点matplotlib.transforms.ScaledTranslation
。
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)
与@explorerDude提供的解决方案相比,此方法的优点是,偏移量与图形中的数据无关,因此偏移量通常适用于任何绘图,并且对于给定的字体大小,其外观相同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句