2017-05-18 1 views
0

enter image description here하기 matplotlib 방법은 라인 바 그래프 주석과

나는 두 기준값 가로대의 값을 비교하는 바 차트에 주석을 작성하고자하는 도면. 직원 계기의 일종 인 그림과 같은 오버레이가 가능하지만 좀 더 세련된 솔루션을 이용할 수 있습니다.

막대 차트는 pandas API를 사용하여 matplotlib (예 : data.plot(kind="bar"))으로 생성되었으므로 솔루션이 멋지게 재생되는 경우 플러스가됩니다.

답변

1

당신은 목표 및 벤치 마크 지표에 대한 작은 막대를 사용할 수 있습니다. 팬더는 자동으로 막대에 주석을 달 수는 없지만 대신 값을 반복하고 matplotlib의 pyplot.annotate을 사용할 수 있습니다.

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 

a = np.random.randint(5,15, size=5) 
t = (a+np.random.normal(size=len(a))*2).round(2) 
b = (a+np.random.normal(size=len(a))*2).round(2) 
df = pd.DataFrame({"a":a, "t":t, "b":b}) 

fig, ax = plt.subplots() 


df["a"].plot(kind='bar', ax=ax, legend=True) 
df["b"].plot(kind='bar', position=0., width=0.1, color="lightblue",legend=True, ax=ax) 
df["t"].plot(kind='bar', position=1., width=0.1, color="purple", legend=True, ax=ax) 

for i, rows in df.iterrows(): 
    plt.annotate(rows["a"], xy=(i, rows["a"]), rotation=0, color="C0") 
    plt.annotate(rows["b"], xy=(i+0.1, rows["b"]), color="lightblue", rotation=+20, ha="left") 
    plt.annotate(rows["t"], xy=(i-0.1, rows["t"]), color="purple", rotation=-20, ha="right") 

ax.set_xlim(-1,len(df)) 
plt.show() 

enter image description here

1

막대 그림에 주석을 달 수있는 직접적인 방법은 없습니다 (필자가 알고있는 한도 내에서) 얼마 전에 필자는 주석을 달아서 이것을 작성 했으므로 필요에 맞게 수정할 수 있습니다. enter image description here

import matplotlib.pyplot as plt 
import numpy as np 

ax = plt.subplot(111) 
ax.set_xlim(-0.2, 3.2) 
ax.grid(b=True, which='major', color='k', linestyle=':', lw=.5, zorder=1) 
# x,y data 
x = np.arange(4) 
y = np.array([5, 12, 3, 7]) 
# Define upper y limit leaving space for the text above the bars. 
up = max(y) * .03 
ax.set_ylim(0, max(y) + 3 * up) 
ax.bar(x, y, align='center', width=0.2, color='g', zorder=4) 
# Add text to bars 
for xi, yi, l in zip(*[x, y, list(map(str, y))]): 
    ax.text(xi - len(l) * .02, yi + up, l, 
      bbox=dict(facecolor='w', edgecolor='w', alpha=.5)) 
ax.set_xticks(x) 
ax.set_xticklabels(['text1', 'text2', 'text3', 'text4']) 
ax.tick_params(axis='x', which='major', labelsize=12) 
plt.show()