Development Tip

Pandas 막대 그림의 값으로 막대에 주석 달기

yourdevel 2020. 12. 29. 08:02
반응형

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

반응형