import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
#Use python 2.7+ syntax to format currency
def money(x, pos):
'The two args are the value and tick position'
return "${:,.0f}".format(x)
formatter = FuncFormatter(money)
#Data to plot. Do not include a total, it will be calculated
index = ['sales','returns','credit fees','rebates','late charges','shipping']
data = {'amount': [350000,-30000,-7500,-25000,95000,-7000]}
#Store data and create a blank series to use for the waterfall
trans = pd.DataFrame(data=data,index=index)
blank = trans.amount.cumsum().shift(1).fillna(0)
#Get the net total number for the final element in the waterfall
total = trans.sum().amount
trans.loc["net"]= total
blank.loc["net"] = total
#The steps graphically show the levels as well as used for label placement
step = blank.reset_index(drop=True).repeat(3).shift(-1)
step[1::3] = np.nan
#When plotting the last element, we want to show the full bar,
#Set the blank to 0
blank.loc["net"] = 0
#Plot and label
my_plot = trans.plot(kind='bar', stacked=True, bottom=blank,legend=None, figsize=(10, 5), title="2014 Sales Waterfall")
my_plot.plot(step.index, step.values,'k')
my_plot.set_xlabel("Transaction Types")
#Format the axis for dollars
my_plot.yaxis.set_major_formatter(formatter)
#Get the y-axis position for the labels
y_height = trans.amount.cumsum().shift(1).fillna(0)
#Get an offset so labels don't sit right on top of the bar
max = trans.max()
neg_offset = max / 25
pos_offset = max / 50
plot_offset = int(max / 15)
#Start label loop
loop = 0
for index, row in trans.iterrows():
# For the last item in the list, we don't want to double count
if row['amount'] == total:
y = y_height[loop]
else:
y = y_height[loop] + row['amount']
# Determine if we want a neg or pos offset
if row['amount'] > 0:
y += pos_offset
else:
y -= neg_offset
my_plot.annotate("{:,.0f}".format(row['amount']),(loop,y),ha="center")
loop+=1
#Scale up the y axis so there is room for the labels
my_plot.set_ylim(0,blank.max()+int(plot_offset))
#Rotate the labels
my_plot.set_xticklabels(trans.index,rotation=0)
my_plot.get_figure().savefig("waterfall.png",dpi=200,bbox_inches='tight')
(1) waterfall chart 참조 링크
Creating a Waterfall Chart in Python - Practical Business Python (pbpython.com)
(2) bar 색상 참조 링크
[색상표] RGB 컬러 색상표 (tistory.com)
(3) chart 여러개 겹치기
(4) 한글 폰트
font_name = font_manager.FontProperties(fname="c:/Windows/Fonts/malgun.ttf").get_name() rc('font', family=font_name)
(5) 수평 bar chart
수평 방향의 bar 차트는 matplotlib.pyplot 모듈의 barh 함수를 사용해 그릴 수 있습니다. barh 함수의 첫 번째 인자는 각 bar가 그려질 위치이고, 두 번째 인자는 각 bar에 대한 수치입니다. 이 값들은 파이썬 리스트 형태로 전달하면 됩니다. align은 bar 차트에서 bar의 정렬 위치를 설정하고 height는 수평 bar 차트의 높이를 설정합니다.
ypos = np.arange(10)
rects = plt.barh(ypos, fluctuations, align='center', height=0.5)
plt.yticks(ypos, industry)
(6) pie chart
import matplotlib.pyplot as plt
ratio = [34, 32, 16, 18]
labels = ['Apple', 'Banana', 'Melon', 'Grapes']
explode = [0.05, 0.05, 0.05, 0.05]
colors = ['#ff9999', '#ffc000', '#8fd9b6', '#d395d0']
plt.pie(ratio, labels=labels, autopct='%.1f%%', startangle=260, counterclock=False, explode=explode, shadow=True, colors=colors)
plt.show()
(7) matplotlib 예제 사이트
20. Matplotlib 파이 차트 그리기 - Matplotlib Tutorial - 파이썬으로 데이터 시각화하기 (wikidocs.net)
(8) matplotlib 그래프 영역 채우기
08. Matplotlib 그래프 영역 채우기 - Matplotlib Tutorial - 파이썬으로 데이터 시각화하기 (wikidocs.net)
반응형
'스타트업 > 업무 자동화' 카테고리의 다른 글
[업무자동화] 파이썬 시각화 패키지 (0) | 2021.07.02 |
---|---|
[업무자동화] DB화 하고 싶은 데이터 목록 (0) | 2021.06.30 |
[업무자동화] 예쁜 보고서 자동으로 만들기 (0) | 2021.06.30 |
[업무자동화] (8) DB 정의서 작성 (0) | 2021.06.17 |
[업무자동화] (7) python scheduler (0) | 2021.06.16 |