2024-05-23|閱讀時間 ‧ 約 22 分鐘

如何用Pthon繪製堆疊直條圖

首先,這是我們的資料:

import pandas as pd

data = pd.read_csv("經濟部能源署_液化天然氣進口來源年資料.csv")
raw-image

然後就可以開始繪圖囉!

import matplotlib

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

from matplotlib import pyplot as plt

#設定堆疊起始值為0
start = 0

#設定圖片大小與子圖位置
plt.figure(figsize=(12,6))
ax = plt.subplot2grid((1,1),(0,0))

#設定迴圈繪圖需要的list
nation_list = ["卡達","澳大利亞","俄羅斯","巴布亞紐幾內亞","印尼","美國","馬來西亞","汶萊","奈及利亞","其他"]
color_list = ["lightcoral","lightsalmon","lightgreen","lightcyan","lightsteelblue","lightyellow","lightseagreen","plum","peru","gray"]

#繪製堆疊直條圖
for i,j in zip(nation_list,color_list):
    ax_x = range(2002,2023)
    ax_y = data[i]

    ax.bar(ax_x,ax_y,bottom=start,color=j,label=i) #bottom是指每次迴圈時直條圖的起始位置

    #讓起始值隨迴圈數增加
    start = start + ax_y

#設定圖例
ax.legend()

#設定標題
ax.set_title("2002-2022 台灣液化天然氣進口量")



分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.