2016-12-17 1 views
1

Matplotlib 그래프의 x 축에 텍스트가 필요합니다. 내가 가진 :Matplotlib (Python)의 막대 차트 그래프에 텍스트 추가

import matplotlib.pyplot as plt 
x=[1,2,3,4,5,6,7,8,9,10,11,12] 
y=[5.3, 6.1, 25.5, 27.8, 31.2, 33.0, 33.0, 32.8, 28.4, 21.1, 17.5, 11.9] 

plt.bar(x,y, color='g') 

plt.xlabel('x') 
plt.ylabel('y') 
plt.title("Max Temperature for Months") 
plt.legend() 
plt.show() 

그리고 내 출력은 다음과 같습니다

My graph

내가 텍스트 (문자열)와 x=[ ] 목록을 교체하는 방법을 모른다, 그것은 나에게 오류를 제공합니다.

내 원하는 그래프는 다음과 같이

My desied graph

+0

도움이 되었다면 내 대답을 수락 할 수 있습니까? 감사합니다 – Chuck

답변

3

plt.xticks() 기능을 사용

import matplotlib.pyplot as plt 
x=[1,2,3,4,5] 
y=[1,2,3,4,5] 

plt.bar(x,y, color='g') 

plt.xlabel('x') 
plt.ylabel('y') 

는 그래프에 가서 몇 가지 레이블을 생성합니다. 문자열의 목록은 xy리스트와 같은 길이이어야합니다

plt.xticks(x, LABELS) 

plt.title("Max Temperature for Months") 
plt.legend() 
plt.show() 

여기에 예를 참조하십시오 : http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html

편집 : 정보에

LABELS = ["M","w","E","R","T"] 

다음 그들을 플롯 라벨의 위치/방향/위치 조정하기, matplotlib api 문서 및이 질문을 참조하십시오 : matplotlib ticks position relative to axis.

편집 : 추가 된 이미지 : http://imgur.com/igjUGLb

편집 : Matplotlib Python Barplot: Position of xtick labels have irregular spaces between eachother : 당신이 필요합니다, 당신은이 질문에 좋은 예를 찾을 위치와 방향을 달성하기 위해.

구현 :

b = plt.bar(x,y, color='g') 
xticks_pos = [0.5*patch.get_width() + patch.get_xy()[0] for patch in b]   
plt.xticks(xticks_pos, LABELS,rotation = 45) 

을 제공합니다 도움이 https://imgur.com/a/78Esz 희망을.

+1

'xticks_pos' 대신'plt.bar (..., align = 'center')'를 사용할 수 있습니다. – unutbu

+1

'LABELS'을 정의하기 위해서'import datetime','x 안에 xi를위한 LABELS = [DT.datetime.strftime (DT.date (2001, xi, 1), '% B')'을 사용할 수 있습니다. – unutbu

+0

@unutbu 훌륭한 조언. 정렬에 대해 완전히 잊었습니다. 훨씬 더 청결한. – Chuck

관련 문제