development

회전 된 xticklabel을 해당 xticks와 정렬

big-blog 2020. 7. 26. 11:35
반응형

회전 된 xticklabel을 해당 xticks와 정렬


아래 그림의 x 축을 확인하십시오. 레이블을 왼쪽으로 조금 움직여 각각의 눈금에 맞출 수 있습니까?

다음을 사용하여 레이블을 회전시킵니다.

ax.set_xticks(xlabels_positions)
ax.set_xticklabels(xlabels, rotation=45)

그러나 보시다시피 회전은 텍스트 레이블의 중앙에 있습니다. 오른쪽으로 이동 한 것처럼 보입니다.

대신 이것을 사용해 보았습니다.

ax.set_xticklabels(xlabels, rotation=45, rotation_mode="anchor")

...하지만 내가 원하는 것을하지 않습니다. 그리고 매개 변수에 "anchor"허용되는 유일한 값 인 것 같습니다 rotation_mode.

예


눈금 레이블의 가로 정렬을 설정할 수 있습니다 (아래 예 참조). 회전 된 레이블 주위에 사각형 상자가 있다고 생각되면 사각형의 어느 쪽을 틱 포인트와 정렬 하시겠습니까?

설명이 필요하면 다음을 원합니다. ha = 'right'

n=5

x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Ticklabel %i' % i for i in range(n)]

fig, axs = plt.subplots(1,3, figsize=(12,3))

ha = ['right', 'center', 'left']

for n, ax in enumerate(axs):
    ax.plot(x,y, 'o-')
    ax.set_title(ha[n])
    ax.set_xticks(x)
    ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])

여기에 이미지 설명을 입력하십시오


Rotating the labels is certainly possible. Note though that doing so reduces the readability of the text. One alternative is to alternate label positions using a code like this:

import numpy as np
n=5

x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]


fig, ax = plt.subplots()
ax.plot(x,y, 'o-')
ax.set_xticks(x)
labels = ax.set_xticklabels(xlabels)
for i, label in enumerate(labels):
    label.set_y(label.get_position()[1] - (i % 2) * 0.075)

여기에 이미지 설명을 입력하십시오

For more background and alternatives, see this post on my blog


An easy, loop-free alternative is to use the horizontalalignment Text property as a keyword argument to xticks[1]. In the below, at the commented line, I've forced the xticks alignment to be "right".

n=5
x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]
fig, ax = plt.subplots()
ax.plot(x,y, 'o-')

plt.xticks(
        [0,1,2,3,4],
        ["this label extends way past the figure's left boundary",
        "bad motorfinger", "green", "in the age of octopus diplomacy", "x"], 
        rotation=45,
        horizontalalignment="right")    # here
plt.show()

(yticks already aligns the right edge with the tick by default, but for xticks the default appears to be "center".)

[1] You find that described in the xticks documentation if you search for the phrase "Text properties".


If you dont want to modify the xtick labels, you can just use:

plt.xticks(rotation=45)

참고 URL : https://stackoverflow.com/questions/14852821/aligning-rotated-xticklabels-with-their-respective-xticks

반응형