반응형
Pandas 막대 그림의 값으로 막대에 주석 달기
내 DataFrame의 둥근 숫자 값으로 Pandas 막대 그림에서 막대에 주석을 달 수있는 방법을 찾고있었습니다.
>>> df=pd.DataFrame({'A':np.random.rand(2),'B':np.random.rand(2)},index=['value1','value2'] )
>>> df
A B
value1 0.440922 0.911800
value2 0.588242 0.797366
다음과 같은 것을 얻고 싶습니다.
이 코드 샘플을 사용해 보았지만 주석은 모두 x 눈금 중심에 있습니다.
>>> ax = df.plot(kind='bar')
>>> for idx, label in enumerate(list(df.index)):
for acc in df.columns:
value = np.round(df.ix[idx][acc],decimals=2)
ax.annotate(value,
(idx, value),
xytext=(0, 15),
textcoords='offset points')
축의 패치에서 직접 가져옵니다.
In [35]: for p in ax.patches:
ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))
문자열 형식과 오프셋을 조정하여 중심에 맞추고 싶을 것입니다. 아마도에서 너비를 사용할 수도 p.get_width()
있지만 시작해야합니다. 오프셋을 어딘가에서 추적하지 않으면 누적 막대 플롯에서 작동하지 않을 수 있습니다.
샘플 부동 형식으로 음수 값도 처리하는 솔루션입니다.
여전히 조정 오프셋이 필요합니다.
df=pd.DataFrame({'A':np.random.rand(2)-1,'B':np.random.rand(2)},index=['val1','val2'] )
ax = df.plot(kind='bar', color=['r','b'])
x_offset = -0.03
y_offset = 0.02
for p in ax.patches:
b = p.get_bbox()
val = "{:+.2f}".format(b.y1 + b.y0)
ax.annotate(val, ((b.x0 + b.x1)/2 + x_offset, b.y1 + y_offset))
참조 URL : https://stackoverflow.com/questions/25447700/annotate-bars-with-values-on-pandas-bar-plots
반응형
'Development Tip' 카테고리의 다른 글
overflow : hidden + display : inline-block이 텍스트를 위로 이동 (0) | 2020.12.29 |
---|---|
C # 동적 유형이 정적 인 이유는 무엇입니까? (0) | 2020.12.29 |
numpy 배열의 요소 이동 (0) | 2020.12.29 |
Webview는 onReceivedSslError 구현시 Google Play의 보안 경고를 방지합니다. (0) | 2020.12.29 |
두 개의 클래스가있는 getElementsByClassName () (0) | 2020.12.29 |