programing

python matplotlib에서 축 문자 회전

kingscode 2022. 10. 8. 16:49
반응형

python matplotlib에서 축 문자 회전

X축의 텍스트를 회전시키는 방법을 알 수 없습니다.타임스탬프이기 때문에 샘플의 수가 증가하면 겹칠 때까지 점점 가까워집니다.샘플이 서로 겹치지 않도록 텍스트를 90도 회전시키고 싶습니다.

아래는 제가 가지고 있는 것입니다만, X축 텍스트를 회전하는 방법을 알 수 없는 것을 제외하고, 정상적으로 동작합니다.

import sys

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import datetime

font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 8}

matplotlib.rc('font', **font)

values = open('stats.csv', 'r').readlines()

time = [datetime.datetime.fromtimestamp(float(i.split(',')[0].strip())) for i in values[1:]]
delay = [float(i.split(',')[1].strip()) for i in values[1:]]

plt.plot(time, delay)
plt.grid(b='on')

plt.savefig('test.png')

이것으로 충분합니다.

plt.xticks(rotation=90)

여기 "정답"이 많이 있는데, 몇 가지 세부 사항이 빠진 것 같아서 하나 더 추가하겠습니다.OP는 90도 회전을 요구했지만, 45도로 변경합니다.왜냐하면 0도나 90도가 아닌 각도를 사용할 때는 수평 정렬도 변경해야 하기 때문입니다.그렇지 않으면 라벨이 중심을 벗어나 약간 오해의 소지가 있기 때문입니다(그리고 여기 오는 많은 사람들은 축을 90도 이외의 것으로 회전하고 싶어할 것입니다).

최단/최단 코드

옵션 1

plt.xticks(rotation=45, ha='right')

앞에서 설명한 바와 같이 객체 지향적 접근 방식을 택하는 경우에는 바람직하지 않을 수 있습니다.

옵션 2

또 다른 빠른 방법(날짜 객체용이지만 모든 레이블에서 작동하는 것 같습니다. 단, 권장되지 않습니다.)

fig.autofmt_xdate(rotation=45)

fig일반적으로 다음에서 얻을 수 있습니다.

  • fig = plt.gcf()
  • fig = plt.figure()
  • fig, ax = plt.subplots()
  • fig = ax.figure

오브젝트 지향 / 직접 대응ax

옵션 3a

라벨 목록이 있는 경우:

labels = ['One', 'Two', 'Three']
ax.set_xticks([1, 2, 3])
ax.set_xticklabels(labels, rotation=45, ha='right')

이후 버전의 Matplotlib(3.5+)에서는set_xticks단독:

ax.set_xticks([1, 2, 3], labels, rotation=45, ha='right')

옵션 3b

현재 그림에서 레이블 리스트를 가져오려는 경우:

# Unfortunately you need to draw your figure first to assign the labels,
# otherwise get_xticklabels() will return empty strings.
plt.draw()
ax.set_xticks(ax.get_xticks())
ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')

위와 같이 Matplotlib(3.5 이상)의 최신 버전에서는set_xticks단독:

ax.set_xticks(ax.get_xticks(), ax.get_xticklabels(), rotation=45, ha='right')

옵션 4

위와 비슷하지만 대신 수동으로 루프를 통과하십시오.

for label in ax.get_xticklabels():
  label.set_rotation(45)
  label.set_ha('right')

옵션 5

우리는 아직 사용하고 있다pyplot(과 같이)plt)는 특정의 속성을 변경하고 있기 때문에 오브젝트 지향적입니다.ax물건.

plt.setp(ax.get_xticklabels(), rotation=45, ha='right')

옵션 6

이 옵션은 간단하지만 AFAIK에서는 라벨 수평 정렬을 이 방법으로 설정할 수 없기 때문에 각도가 90이 아니면 다른 옵션이 더 나을 수 있습니다.

ax.tick_params(axis='x', labelrotation=45)

편집: 이 "버그"에 대한 설명이 있지만 수정이 발표되지 않았습니다(현재).3.4.0): https://github.com/matplotlib/matplotlib/issues/13774

쉬운 방법

여기서 설명한 바와 같이 에는 기존 방식이 있습니다.matplotlib.pyplot figure사용자의 그림에 맞게 자동으로 날짜를 회전하는 클래스입니다.

데이터를 플롯한 후에 호출할 수 있습니다(예:ax.plot(dates,ydata):

fig.autofmt_xdate()

라벨의 포맷이 필요한 경우는, 위의 링크를 확인해 주세요.

비데이터타임 객체

languitar의 코멘트에 따르면, 제가 제안한 비데이타임 방법은xticks확대/축소할 때 올바르게 갱신되지 않는다.가 아니면datetimeX축 데이터로 사용되는 오브젝트는 Tommy의 답변따라야 합니다.

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

pyplot.setp를 시도합니다.내 생각엔 이렇게 할 수 있을 것 같아요.

x = range(len(time))
plt.xticks(x,  time)
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.plot(x, delay)

첨부 파일

plt.xticks(rotation=90)

이것도 가능합니다.

plt.xticks(rotation='vertical')

나도 비슷한 예를 생각해 냈다.rotation 키워드는...음, 열쇠야.

from pylab import *
fig = figure()
ax = fig.add_subplot(111)
ax.bar( [0,1,2], [1,3,5] )
ax.set_xticks( [ 0.5, 1.5, 2.5 ] )
ax.set_xticklabels( ['tom','dick','harry'], rotation=45 ) ;

은 " " "를 사용하는 입니다.tick_params를 들어예를들면.

ax.tick_params(axis='x', labelrotation=90)

Matplotlib 설명서 참조.

할 때 합니다.plt.subplots합니다.set_xticks 이 , (도 편리하기 입니다.

「 」를 하고 있는 plt:

plt.xticks(rotation=90)

팬더나 바다소른을 이용해 음모를 꾸미는 경우,ax다음 중 하나:

ax.set_xticklabels(ax.get_xticklabels(), rotation=90)

위의 다른 방법으로는 다음과 같습니다.

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

제 답변은 cjohnson318의 답변에서 영감을 얻었지만, 하드코드화된 라벨 목록을 제공하고 싶지 않았습니다.기존 라벨을 회전시키고 싶었습니다.

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

가장 간단한 해결책은 다음과 같습니다.

plt.xticks(rotation=XX)

하지만 또한

# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=X.XX)

예: 회전=45 및 하단=0.20을 사용한 날짜에 대해 일부 테스트를 수행할 수 있습니다.

import pylab as pl
pl.xticks(rotation = 90)

x축 레이블을 90도로 회전하는 방법

for tick in ax.get_xticklabels():
    tick.set_rotation(45)

네가 뭘 꾸미느냐에 따라 다르겠지

import matplotlib.pyplot as plt

 x=['long_text_for_a_label_a',
    'long_text_for_a_label_b',
    'long_text_for_a_label_c']
y=[1,2,3]
myplot = plt.plot(x,y)
for item in myplot.axes.get_xticklabels():
    item.set_rotation(90)

Axis 객체를 제공하는 팬더 및 시보른의 경우:

df = pd.DataFrame(x,y)
#pandas
myplot = df.plot.bar()
#seaborn 
myplotsns =sns.barplot(y='0',  x=df.index, data=df)
# you can get xticklabels without .axes cause the object are already a 
# isntance of it
for item in myplot.get_xticklabels():
    item.set_rotation(90)

경우도 .font_scale=1.0네, 그렇습니다.

언급URL : https://stackoverflow.com/questions/10998621/rotate-axis-text-in-python-matplotlib

반응형