如何用Python繪製區域圖?

更新 發佈閱讀 4 分鐘

首先,這是我們的資料:

import pandas as pd

data = pd.read_excel("勞工保險基金每月經營概況.xlsx")
raw-image

接著處理一下資料:

data["基金運用餘額(億元)"] = (data["基金運用餘額(金額)"]/100000000).astype("int")

data["基金收益數(億元)"] = (data["基金收益數(金額)"]/100000000).astype("int")

data["年月"] = list(map(lambda x: str(x)[0:4]+"\n"+str(x)[5:7],data["月別"]))

data.drop(columns=["月別","基金運用餘額(金額)","基金收益數(金額)"],inplace=True)
raw-image


利用迴圈計算累積收益:

maonylist = []

x = 0
for i in data["基金收益數(億元)"]:
    x = i + x
    maonylist.append(x)

data["累積基金收益數(億元)"] = pd.Series(maonylist)
raw-image

整理好資料,我們就可以來繪圖了:

import matplotlib

#設定中文字型​
matplotlib.rc("font",family="Microsoft Yahei")

from matplotlib import pyplot as plt

#設定圖表大小​
plt.figure(figsize=(12,6))

#設定子圖位置​
ax = plt.subplot2grid((1,1),(0,0))

#設定x、y資料​
ax_x = data["年月"]
ax_y1 = data["基金收益數(億元)"]
ax_y2 = data["累積基金收益數(億元)"]
ax_y3 = data["基金運用餘額(億元)"]

#區域圖(fill_between(x,y1,y2)):填充y1、y2間的面積​
ax.fill_between(ax_x,ax_y3,0,label="基金運用餘額",color="darkgray",alpha=0.5)
ax.fill_between(ax_x,ax_y2,0,label="累積基金收益數",color="green",alpha=0.5)
ax.fill_between(ax_x,ax_y1,0,label="基金收益數",color="lightgreen",alpha=0.5)

#設定y軸參數​
ax.set_ylim(0,10000)
ax.set_yticks([2500,5000,7500,10000,12500])
ax.set_yticklabels(["2千\n500億","5千億","7千\n500億","1兆","1兆\n2500億"])

#設定圖例​
ax.legend(loc="upper left")

#設定文字​
for a,b,c,d in zip(ax_x,ax_y1,ax_y2,ax_y3):
    ax.text(a,b+150,str(b)+"億",horizontalalignment="center",color="lightgreen")
    ax.text(a,c+150,str(c)+"億",horizontalalignment="center",color="green")
    ax.text(a,d+150,str(d)+"億",horizontalalignment="center",color="darkgray")

#設定標題​
ax.set_title("2023年3月至2024年3月\n勞工保險基金每月經營概況")
raw-image



留言
avatar-img
留言分享你的想法!
avatar-img
果農的沙龍
7會員
61內容數
我是果農,這裡有我的人資職涯經驗分享,與我菜鳥般的Python資料分析筆記,還有一些讀書心得,希望對大家有幫助。
果農的沙龍的其他內容
2024/08/30
如何用Python做可調整是否能重複抽獎的程式
Thumbnail
2024/08/30
如何用Python做可調整是否能重複抽獎的程式
Thumbnail
2024/08/23
如何用Python繪製彩色表格
Thumbnail
2024/08/23
如何用Python繪製彩色表格
Thumbnail
2024/08/23
如何調整成Python的日期格式
Thumbnail
2024/08/23
如何調整成Python的日期格式
Thumbnail
看更多
你可能也想看
Thumbnail
介紹如何用assign函數在Python中建立新欄位
Thumbnail
介紹如何用assign函數在Python中建立新欄位
Thumbnail
本文在介紹如何用Python繪製各點大小不同的散布圖及用箭頭標註特殊點
Thumbnail
本文在介紹如何用Python繪製各點大小不同的散布圖及用箭頭標註特殊點
Thumbnail
本文將介紹如何用Python繪製群組直條圖。
Thumbnail
本文將介紹如何用Python繪製群組直條圖。
Thumbnail
本文介紹如何用Python繪製散布圖與迴歸線
Thumbnail
本文介紹如何用Python繪製散布圖與迴歸線
Thumbnail
這篇文章介紹如何使用Python整理資料成百分比資料以及繪製百分比堆疊直條圖。
Thumbnail
這篇文章介紹如何使用Python整理資料成百分比資料以及繪製百分比堆疊直條圖。
追蹤感興趣的內容從 Google News 追蹤更多 vocus 的最新精選內容追蹤 Google News