[Visualization] x 축에 중복된 이름 잘 시각화하기 (xticks) (1/2)

2020. 11. 19. 23:59분석 Python/Visualization

728x90

2020/11/19 - [분석 Python/Visualization] - [Visualization] x 축에 중복된 이름 잘 시각화하기 (xticks) (1/2)

2020/11/19 - [분류 전체보기] - [Visualization] x 축에 있는 margin 제거하기 (2/2)

index = np.random.choice(list("abcdefghijklmn"),size=100).reshape(-1,1)
y = np.random.normal(size=100).reshape(-1,1)
result = pd.DataFrame(np.concatenate([index,y],axis=1),columns=["name","target"])
result = result.sort_values(["name"])

 

보통 레이블을 달 경우네는 다음과 같이 xticks에다가 레이블을 붙인다.

하지만 아래 그림을 보면 중복된 이름을 넣다 보니, 중복되는 것이 연달아 나온 것을 확인할 수 있다.

그래서 이러한 그림은 어떻게 보면 예쁘지 않기 때문에 예쁘게 시각화하는 방법을 공유한다.

plt.figure(figsize=(17,10))
plt.subplots_adjust(left=0.2, bottom=0.5, right=0.99, 
                    top=0.97, wspace=0.05, hspace=0.1)
plt.plot(np.arange(len(result)), result["target"], label ="true")
plt.legend()
plt.xticks(ticks=np.arange(len(result)), labels = result["name"])
plt.show()

일단 중복되는 이름의 위치를 찾는 것부터 한다.

drop_duplicated 를 사용해서 index를 추출한다.

uni_list = result["name"].drop_duplicates(keep="first")
ticks = uni_list.index.tolist()
labels = uni_list.values.tolist()

그다음에 아무것도 표시를 안 해줘도 되지만, 여백의 미보다는 표시를 해주면 좋을 것 같아서 다음과 같이 "-" 표시를 해주는 코드다.

labels = [dict(zip(ticks , labels))[i] if i in ticks else "-"  for i in range(len(result)) ]
ticks = np.arange(len(result))

아래에 여러가지 복잡하게 설정하면, 어느 경우에나 작동되는 코드를 얻을 수 있다!

plt.figure(figsize=(17,17))
plt.subplots_adjust(left=0.2, bottom=0.5, right=0.99, 
                    top=0.97, wspace=0.05, hspace=0.1)
plt.plot(np.arange(len(result)), result["target"], label ="true")
plt.xticks(ticks = ticks, labels=labels,rotation=0,size=12, va='top', ha='right')
plt.legend()
plt.gca().margins(x=0.1)
plt.gcf().canvas.draw()
tl = plt.gca().get_xticklabels()
maxsize = max([t.get_window_extent().width for t in tl])
m = 0.05 # inch margin
s = maxsize/plt.gcf().dpi*len(exp_result)+2*m
margin = m/plt.gcf().get_size_inches()[0]
plt.gcf().subplots_adjust(left=margin, right=1.-margin)
plt.gcf().set_size_inches(s, plt.gcf().get_size_inches()[1])
plt.show()

 

하지만 이 그림에서 아쉬운 부분이 있다.

바로 여백이 엄청 생긴다는 것이다.

 

이것을 해결하는 것은 다음장에서...

 

아마 이름이 이상해서 잘 못 들어오지 않을까 싶다..

혹시 읽으신 분들 중에서 글 제목 추천도 부탁드립니다!

 

다음 글 링크

2020/11/19 - [분류 전체보기] - [Visualization] x 축에 있는 margin 제거하기 (2/2)

728x90