用 Python 制作銷售數據可視化看板,展示分析一步到位


在數據時代,銷售數據分析的重要性已無需贅言。

 

只有對銷售數據的准確分析我們才有可能找准數據變動(增長或下滑)的原因。

 

然后解決問題、發現新的增長點才會成為可能!

 

今天就給大家介紹一個用Python制作銷售數據大屏的方法。

 

主要使用Python的Streamlit庫、Plotly庫、Pandas庫進行搭建。

其中Pandas處理數據,Plotly制作可視化圖表,Streamlit搭建可視化頁面。

 

對於以上三個庫,Streamlit庫可能大家會比較陌生,我簡單介紹一下。

 

Streamlit是一個完全免費的開源應用程序框架,它能幫你不用懂得復雜的HTML,CSS等前端技術就能快速做出來一個炫酷的Web頁面。

 

文檔地址

https://docs.streamlit.io/

 

具體的大家可以去看文檔學習,多動手練習。

 

下面就給大家講解一下如何搭建銷售數據看板~

 

 

01. 數據

 

使用的數據是虛構數據,某超市2021年銷售訂單數據,共有1000條的訂單數據。

城市有三個,分別為北京、上海、杭州。顧客類型有兩種,為會員和普通。顧客性別為男性和女性。

 

剩下還包含訂單編號、商品類型、單價、數量、總價、日期、時間、支付方式、成本、毛利率、總收入、評分等信息。

 

通用Pandas的read_excel方法讀取數據。

 

跳過前3行,選取B到R列,1000行數據。

def get_data_from_excel():
    df = pd.read_excel(
        io="supermarkt_sales.xlsx",
        engine="openpyxl",
        sheet_name="Sales",
        skiprows=3,
        usecols="B:R",
        nrows=1000,
    )
    # 添加小時列數據
    df["小時"] = pd.to_datetime(df["時間"], format="%H:%M:%S").dt.hour
    return df

df = get_data_from_excel()
print(df)

成功讀取數據,結果如下。

下面便可以來編寫頁面了。

 

 

02. 網頁標題和圖標

 

我們都知道當瀏覽器打開一個網頁,會有標題和圖標。

所以我們需先設置本次網頁的名稱、圖標、布局等。

 

這也是使用Streamlit搭建頁面,使用的第一個Streamlit命令,並且只能設置一次。

 

# 設置網頁信息 
st.set_page_config(page_title="銷售數據大屏", page_icon=":bar_chart:", layout="wide")

其中page_icon參數可以使用表情符號代碼來顯示圖標。

 

短代碼可從下方鏈接獲取。

https://www.webfx.com/tools/emoji-cheat-sheet/

妥妥的表情符號代碼大全!

 

 

03. 側邊欄和多選框

 

st.sidebar(側邊欄),每個傳遞給st.sidebar的元素都會被固定在左邊,讓用戶可以專注於主頁中的內容。

 

multiselect(多選框)是一個交互性的部件,可以通過它進行數據篩選。

# 側邊欄
st.sidebar.header("請在這里篩選:")
city = st.sidebar.multiselect(
    "選擇城市:",
    options=df["城市"].unique(),
    default=df["城市"].unique()
)

customer_type = st.sidebar.multiselect(
    "選擇顧客類型:",
    options=df["顧客類型"].unique(),
    default=df["顧客類型"].unique(),
)

gender = st.sidebar.multiselect(
    "選擇性別:",
    options=df["性別"].unique(),
    default=df["性別"].unique()
)

df_selection = df.query(
    "城市 == @city & 顧客類型 ==@customer_type & 性別 == @gender"
)

結合Pandas的query查詢,就能對數據進行過濾。

 

通過上述代碼就搭建成功了,如下圖左側。

點擊側邊欄的右上角關閉符號,側邊欄即可隱藏。

 

網頁將會展示主頁面。

04. 主頁面信息

 

接下來編寫主頁面信息,包含主頁標題、銷售總額、平均評分、平均銷售額信息。

 

和網頁的圖標一樣,通過表情符號代碼實現。

# 主頁面
st.title(":bar_chart: 銷售數據大屏")
st.markdown("##")

# 核心指標, 銷售總額、平均評分、星級、平均銷售額數據
total_sales = int(df_selection["總價"].sum())
average_rating = round(df_selection["評分"].mean(), 1)
star_rating = ":star:" * int(round(average_rating, 0))
average_sale_by_transaction = round(df_selection["總價"].mean(), 2)


# 3列布局
left_column, middle_column, right_column = st.columns(3)

# 添加相關信息
with left_column:
    st.subheader("銷售總額:")
    st.subheader(f"RMB {total_sales:,}")
with middle_column:
    st.subheader("平均評分:")
    st.subheader(f"{average_rating} {star_rating}")
with right_column:
    st.subheader("平均銷售額:")
    st.subheader(f"RMB {average_sale_by_transaction}")

# 分隔符
st.markdown("""---""")

完成核心指標數據的處理,並將其進行布局顯示。

05. 主頁面圖表

 

包含了兩個圖表,一個是每小時銷售額,一個是各類商品銷售總額。通過Plotly Express完成圖表的繪制。

 

Plotly Express是一個新的高級Python可視化庫,是Plotly.py的高級封裝,它為復雜的圖表提供了一個簡單的語法。

 

文檔地址

https://plot.ly/python/plotly-express/

 

受Seaborn和ggplot2的啟發,它專門設計為具有簡潔,一致且易於學習的API。只需一次導入,就可以在一個函數調用中創建豐富的交互式繪圖。

# 各類商品銷售情況(柱狀圖)
sales_by_product_line = (
    df_selection.groupby(by=["商品類型"]).sum()[["總價"]].sort_values(by="總價")
)
fig_product_sales = px.bar(
    sales_by_product_line,
    x="總價",
    y=sales_by_product_line.index,
    orientation="h",
    title="<b>每種商品銷售總額</b>",
    color_discrete_sequence=["#0083B8"] * len(sales_by_product_line),
    template="plotly_white",
)
fig_product_sales.update_layout(
    plot_bgcolor="rgba(0,0,0,0)",
    xaxis=(dict(showgrid=False))
)

# 每小時銷售情況(柱狀圖)
sales_by_hour = df_selection.groupby(by=["小時"]).sum()[["總價"]]
print(sales_by_hour.index)
fig_hourly_sales = px.bar(
    sales_by_hour,
    x=sales_by_hour.index,
    y="總價",
    title="<b>每小時銷售總額</b>",
    color_discrete_sequence=["#0083B8"] * len(sales_by_hour),
    template="plotly_white",
)
fig_hourly_sales.update_layout(
    xaxis=dict(tickmode="linear"),
    plot_bgcolor="rgba(0,0,0,0)",
    yaxis=(dict(showgrid=False)),
)


left_column, right_column = st.columns(2)
left_column.plotly_chart(fig_hourly_sales, use_container_width=True)
right_column.plotly_chart(fig_product_sales, use_container_width=True)

添加數據,設置圖表配置,以及網頁布局。

 

得到結果如下。

06. 隱藏部件

 

當我們通過Streamlit搭建一個界面,默認就會有紅線、菜單、結尾的"Make with Streamlit"。

為了美觀,這里可以將它們都隱藏掉。

# 隱藏streamlit默認格式信息
hide_st_style = """
            <style>
            #MainMenu {visibility: hidden;}
            footer {visibility: hidden;}
            header {visibility: hidden;}
            </style>
            """

st.markdown(hide_st_style, unsafe_allow_html=True)

 

這樣一個可交互的銷售數據看板,就完成搭建啦!

 

# 安裝依賴庫
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple plotly==4.14.3
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pandas==1.1.0
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple streamlit==0.86.0
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple openpyxl==3.0.6

# 運行
streamlit run app.py

 

安裝相關依賴,命令行終端運行程序。

轉自https://mp.weixin.qq.com/s/pZURditY0Z2WYpZK3VhLwg

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM