import pandas as pd import numpy as np
#테이블 만들기 consult = pd.read_csv("C:\\data\\consult.csv") x1 = consult[['년도', '품목', '성별']]
x1['남성'] = x1['성별'][x1['성별'] == '남성'] x1['여성'] = x1['성별'][x1['성별'] == '여성']
result1 = x1.groupby('년도')['남성'].count().reset_index() result2 = x1.groupby('년도')['여성'].count().reset_index() result6 = x1.groupby('년도')['품목'].count().reset_index() result7 = result6[['품목']].astype(int) #증감률 a=[] for i in np.arange(0,4): result3 = round(((result7.loc[i+1] - result7.loc[i]) / result7.loc[i])*100,2) #print(result3[0]) a.append(result3[0]) #print(a)
a.insert(0,0)
result_df = pd.DataFrame({'증감률':a}) #print(result_df)
result4 = pd.merge(result1,result2,on='년도') result4_1 = pd.merge(result4,result6,on='년도')
table1=pd.concat([result4_1,result_df],axis=1) table1 = table1.fillna(0) table1.columns=['년도','남성','여성','총건수','증감률']
#그래프 생성
from matplotlib import font_manager, rc import matplotlib.ticker as ticker import matplotlib.pyplot as plt import matplotlib.patches as patches
# 한글 깨지지 않게 하는 코드 font = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name() rc('font', family=font)
# 스타일지정 plt.style.use('ggplot')
# 그래프 색 코드를 리스트로 저장 colors = [ ['#004ACD', '#00163D'], ['#FF0000', '#4D0000'], ['#00B798', '#00372E'], ]
bar_xrange = np.arange(len(table1['년도'].values)) # 막대 그래프의 x축 범위 설정 bar_thickness = 0.40 # 막대 그래프 두께 변수 line_passvalue = table1['증감률'].values
fig, ax1 = plt.subplots(figsize = (10, 5))
# 남성 막대 그래프 표시 bar1 = ax1.bar(bar_xrange - bar_thickness, '남성', data = table1, width = bar_thickness, color = colors[0][0], align = 'edge', label = '남성', alpha = 0.65, tick_label = '년도')
# 남성 막대 그래프 위 숫자 표시 for rect in bar1 : height = rect.get_height() plt.text(rect.get_x() + rect.get_width()/2.0, height, format(height, ','), ha = 'center', va = 'bottom', color = colors[0][1], size = 10.5)
# 여성 막대 그래프 표시 bar2 = ax1.bar(bar_xrange, '여성', data = table1, width = bar_thickness, color = colors[1][0], align = 'edge', label = '여성', alpha = 0.65, tick_label = '년도')
# 여성 막대 그래프 위 숫자 표시 for idx, rect in enumerate(bar2) : height = rect.get_height() + 40 if idx in [3, 8] else (rect.get_height() - 100) if idx in [17, 18] else rect.get_height() plt.text(rect.get_x() + rect.get_width()/2.0, height, format(rect.get_height(), ','), ha = 'center', va = 'bottom', color = colors[1][1], size = 10.5)
# 막대 그래프 영역 축 설정 ax1.set_xlim(-1, 5) ax1.set_ylim(0, 180000) ax1.set_xticks(range(0, 5)) ax1.set_yticks(range(0, 180000 + 1, 20000))
plt.xticks(rotation = 0, size = 11) plt.yticks(size = 11)
# 증감률 표시를 위한 보조축 생성 ax2 = ax1.twinx()
# 증감률 선 그래프 표시 line1 = ax2.plot(bar_xrange, '증감률', data = table1, marker = 's', markersize = 6, linewidth = 2, color = colors[2][0], alpha = 0.65)
# 증감률 선 그래프 위 숫자 표시 for i in range(len(bar_xrange)) : try : # 선 그래프 표시 위치 설정 (상/하 위치에 따라 변경) if (line_passvalue[i] < line_passvalue[i - 1]) & (line_passvalue[i] < line_passvalue[i + 1]) : height = line_passvalue[i] - 3.75 else : raise IndexError
except IndexError : height = line_passvalue[i] + 1.25
plt.text(bar_xrange[i], height, ('%.1f%%' %(line_passvalue[i])), ha = 'center', va = 'bottom', size = 10.5, color = colors[2][1])
# 선 그래프 영역 축 설정 ax2.set_xlim(-1, 5) ax2.set_ylim(-500,100) ax2.set_yticks(range(100, 200, 20)) plt.grid(False)
ax2.axes.yaxis.set_visible(False) # 왼쪽 y축 천 단위 표시 ax1.get_yaxis().set_major_formatter(ticker.FuncFormatter(lambda x, p: format(x, ',')))
# 오른쪽 y축 %표시 ax2.get_yaxis().set_major_formatter(ticker.FuncFormatter(lambda x, p: str(x) + '%'))
plt.title('년도별 전년대비 증감률 및 성별에 따른 상담 총건수', pad = 15, fontsize = 17,fontweight='bold') plt.yticks(size = 11)
#남성,여성라벨설정 variable_x = patches.Patch(color=colors[0][0],label='남성') variable_y = patches.Patch(color=colors[1][0],label='여성') plt.legend(handles=[variable_x, variable_y])
#사각형삽입 shp1=patches.Rectangle((2.5,-250),2,200 ,edgecolor='r',fill=False, linestyle='dashed',linewidth=2) shp2=patches.Arrow(1.3,150,0.5,0,width=50 ,edgecolor='black',linestyle='solid',linewidth=1.5, fill=True,facecolor='red')
box1 = {'boxstyle': 'round', 'ec': (1.0, 0.5, 0.5), 'fc': (1.0, 0.8, 0.8)}
plt.gca().add_patch(shp1) plt.gca().add_patch(shp2) plt.gca().text(0.25,150,"증감률이 높은 지점",fontsize=12, fontweight='bold',bbox=box1) plt.gca().text(2.5,-20,"비교할 년도",fontsize=12,fontweight='bold',bbox=box1)
#plt.text(2.5, -20, 'check year', fontdict=font1, bbox=box1) #plt.text(0.75,150, 'high point',fontdict=font1,bbox=box1) fig.tight_layout() plt.show() |