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)

 

Creating a Waterfall Chart in Python - Practical Business Python

Tue 18 November 2014 Posted by Chris Moffitt in articles    Introduction Waterfall charts can be a really useful tool to for certain types of data plotting. Not surprisingly, we can use pandas and matplotlib to create a repeatable waterfall chart. Befor

pbpython.com

 

(2) bar 색상 참조 링크

[색상표] RGB 컬러 색상표 (tistory.com)

 

[색상표] RGB 컬러 색상표

안녕하세요~  블로그지기 인간대표 입니다. RGB 색상표 입니다. 컬러 이름 및 코드를 알 수 있습니다. 색상 256 복합수 16진수 코드 Snow 255 250 250 #FFFAFA GhostWhite 248 248 255 #F8F8FF WhiteSmoke 245..

cityattack.tistory.com

 

(3) chart 여러개 겹치기

[Stock_Magnifier 주식 툴] 한 차트 내에서 2개 종목 주가 그리기 파이썬 코드 (동일업종 2개 종목 비교, 한국 vs. 미국 종목 비교도 가능 ^^) : 네이버 블로그 (naver.com)

 

[Stock_Magnifier 주식 툴] 한 차트 내에서 2개 종목 주가 그리기 파이썬 코드 (동일업종 2개 종목 비교

조카님들 안녕하세요. #재테크 목적으로 #파이썬 #금융라이브러리 를 최대한 잘 활용해보고픈 코딩 읽어주...

blog.naver.com

 

(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)

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net

(8) matplotlib 그래프 영역 채우기

08. Matplotlib 그래프 영역 채우기 - Matplotlib Tutorial - 파이썬으로 데이터 시각화하기 (wikidocs.net)

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net

 

반응형

+ Recent posts