1. 程式人生 > >吳裕雄 資料探勘與分析案例實戰(5)——python資料視覺化

吳裕雄 資料探勘與分析案例實戰(5)——python資料視覺化

# 餅圖的繪製
# 匯入第三方模組
import matplotlib
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif']=['Simhei']
plt.rcParams['axes.unicode_minus']=False
ziti = matplotlib.font_manager.FontProperties(fname='C:\Windows\Fonts\simsun.ttc')

# 構造資料
edu = [0.2515,0.3724,0.3336,0.0368,0.0057]
labels = ['中專','大專','本科','碩士','其他']
# 繪製餅圖
plt.pie(x = edu, # 繪圖資料
labels=labels, # 新增教育水平標籤
autopct='%.1f%%' # 設定百分比的格式,這裡保留一位小數
)
# 新增圖示題
plt.title('失信使用者的教育水平分佈')
# 顯示圖形
plt.show()

# 構造資料
edu = [0.2515,0.3724,0.3336,0.0368,0.0057]
labels = ['中專','大專','本科','碩士','其他']
# 新增修飾的餅圖
explode = [0,0.1,0,0,0] # 生成資料,用於突出顯示大專學歷人群
colors=['#9999ff','#ff9999','#7777aa','#2442aa','#dd5555'] # 自定義顏色
# 中文亂碼和座標軸負號的處理
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
# 將橫、縱座標軸標準化處理,確保餅圖是一個正圓,否則為橢圓
plt.axes(aspect='equal')
# 繪製餅圖
plt.pie(x = edu, # 繪圖資料
explode=explode, # 突出顯示大專人群
labels=labels, # 新增教育水平標籤
colors=colors, # 設定餅圖的自定義填充色
autopct='%.1f%%', # 設定百分比的格式,這裡保留一位小數
pctdistance=0.8, # 設定百分比標籤與圓心的距離
labeldistance = 1.1, # 設定教育水平標籤與圓心的距離
startangle = 180, # 設定餅圖的初始角度
radius = 1.2, # 設定餅圖的半徑
counterclock = False, # 是否逆時針,這裡設定為順時針方向
wedgeprops = {'linewidth': 1.5, 'edgecolor':'green'},# 設定餅圖內外邊界的屬性值
textprops = {'fontsize':10, 'color':'black'}, # 設定文字標籤的屬性值
)
# 新增圖示題
plt.title('失信使用者的受教育水平分佈')
# 顯示圖形
plt.show()

# 匯入第三方模組
import pandas as pd
import matplotlib.pyplot as plt
# 構建序列
data1 = pd.Series({'中專':0.2515,'大專':0.3724,'本科':0.3336,'碩士':0.0368,'其他':0.0057})
print(data1)
data1.name = ''
# 控制餅圖為正圓
plt.axes(aspect = 'equal')
# plot方法對序列進行繪圖
data1.plot(kind = 'pie', # 選擇圖形型別
autopct='%.1f%%', # 餅圖中新增數值標籤
radius = 1, # 設定餅圖的半徑
startangle = 180, # 設定餅圖的初始角度
counterclock = False, # 將餅圖的順序設定為順時針方向
title = '失信使用者的受教育水平分佈', # 為餅圖新增標題
wedgeprops = {'linewidth': 1.5, 'edgecolor':'green'}, # 設定餅圖內外邊界的屬性值
textprops = {'fontsize':10, 'color':'black'} # 設定文字標籤的屬性值
)
# 顯示圖形
plt.show()

# 條形圖的繪製--垂直條形圖
# 讀入資料
GDP = pd.read_excel(r'F:\\python_Data_analysis_and_mining\\06\\Province GDP 2017.xlsx')
# 設定繪圖風格(不妨使用R語言中的ggplot2風格)
plt.style.use('ggplot')
# 繪製條形圖
plt.bar(left = range(GDP.shape[0]), # 指定條形圖x軸的刻度值
height = GDP.GDP, # 指定條形圖y軸的數值
tick_label = GDP.Province, # 指定條形圖x軸的刻度標籤
color = 'steelblue', # 指定條形圖的填充色
)
# 新增y軸的標籤
plt.ylabel('GDP(萬億)')
# 新增條形圖的標題
plt.title('2017年度6個省份GDP分佈')
# 為每個條形圖新增數值標籤
for x,y in enumerate(GDP.GDP):
plt.text(x,y+0.1,'%s' %round(y,1),ha='center')
# 顯示圖形
plt.show()

# 條形圖的繪製--水平條形圖
# 對讀入的資料作升序排序
GDP.sort_values(by = 'GDP', inplace = True)
# 繪製條形圖
plt.barh(bottom = range(GDP.shape[0]), # 指定條形圖y軸的刻度值
width = GDP.GDP, # 指定條形圖x軸的數值
tick_label = GDP.Province, # 指定條形圖y軸的刻度標籤
color = 'steelblue', # 指定條形圖的填充色
)
# 新增x軸的標籤
plt.xlabel('GDP(萬億)')
# 新增條形圖的標題
plt.title('2017年度6個省份GDP分佈')
# 為每個條形圖新增數值標籤
for y,x in enumerate(GDP.GDP):
plt.text(x+0.1,y,'%s' %round(x,1),va='center')
# 顯示圖形
plt.show()

# 條形圖的繪製--堆疊條形圖
# 讀入資料
Industry_GDP = pd.read_excel(r'F:\\python_Data_analysis_and_mining\\06\\Industry_GDP.xlsx')
print(Industry_GDP.head())
# 取出四個不同的季度標籤,用作堆疊條形圖x軸的刻度標籤
Quarters = Industry_GDP.Quarter.unique()
print(Quarters)
# 取出第一產業的四季度值
Industry1 = Industry_GDP.GPD[Industry_GDP.Industry_Type == '第一產業']
print(Industry1)
# 重新設定行索引
Industry1.index = range(len(Quarters))
print(Industry1)
# 取出第二產業的四季度值
Industry2 = Industry_GDP.GPD[Industry_GDP.Industry_Type == '第二產業']
print(Industry2)
# 重新設定行索引
Industry2.index = range(len(Quarters))
print(Industry2)
# 取出第三產業的四季度值
Industry3 = Industry_GDP.GPD[Industry_GDP.Industry_Type == '第三產業']
print(Industry3)

# 繪製堆疊條形圖
# 各季度下第一產業的條形圖
plt.bar(left = range(len(Quarters)), height=Industry1, color = 'steelblue', label = '第一產業', tick_label = Quarters)
# 各季度下第二產業的條形圖
plt.bar(left = range(len(Quarters)), height=Industry2, bottom = Industry1, color = 'green', label = '第二產業')
# 各季度下第三產業的條形圖
plt.bar(left = range(len(Quarters)), height=Industry3, bottom = Industry1 + Industry2, color = 'red', label = '第三產業')
# 新增y軸標籤
plt.ylabel('生成總值(億)')
# 新增圖形標題
plt.title('2017年各季度三產業總值')
# 顯示各產業的圖例
plt.legend()
# 顯示圖形
plt.show()

# Pandas模組之垂直或水平條形圖
# 繪圖(此時的資料集在前文已經按各省GDP做過升序處理)
GDP.GDP.plot(kind = 'bar', width = 0.8, rot = 0, color = 'steelblue', title = '2017年度6個省份GDP分佈')
# 新增y軸標籤
plt.ylabel('GDP(萬億)')
# 新增x軸刻度標籤
plt.xticks(range(len(GDP.Province)), #指定刻度標籤的位置
GDP.Province # 指出具體的刻度標籤值
)
# 為每個條形圖新增數值標籤
for x,y in enumerate(GDP.GDP):
plt.text(x-0.1,y+0.2,'%s' %round(y,1),va='center')
# 顯示圖形
plt.show()

# 條形圖的繪製--水平交錯條形圖
# 匯入第三方模組
import numpy as np
# 讀入資料
HuRun = pd.read_excel(r'F:\\python_Data_analysis_and_mining\\06\\HuRun.xlsx')
# 取出城市名稱
Cities = HuRun.City.unique()
# 取出2016年各城市億萬資產家庭數
Counts2016 = HuRun.Counts[HuRun.Year == 2016]
# 取出2017年各城市億萬資產家庭數
Counts2017 = HuRun.Counts[HuRun.Year == 2017]

# 繪製水平交錯條形圖
bar_width = 0.4
plt.bar(left = np.arange(len(Cities)), height = Counts2016, label = '2016', color = 'steelblue', width = bar_width)
plt.bar(left = np.arange(len(Cities))+bar_width, height = Counts2017, label = '2017', color = 'indianred', width = bar_width)
# 新增刻度標籤(向右偏移0.225)
plt.xticks(np.arange(5)+0.2, Cities)
# 新增y軸標籤
plt.ylabel('億萬資產家庭數')
# 新增圖形標題
plt.title('近兩年5個城市億萬資產家庭數比較')
# 新增圖例
plt.legend()
# 顯示圖形
plt.show()

# Pandas模組之水平交錯條形圖
HuRun_reshape = HuRun.pivot_table(index = 'City', columns='Year', values='Counts').reset_index()
# 對資料集降序排序
HuRun_reshape.sort_values(by = 2016, ascending = False, inplace = True)
HuRun_reshape.plot(x = 'City', y = [2016,2017], kind = 'bar', color = ['steelblue', 'indianred'],
rot = 0, # 用於旋轉x軸刻度標籤的角度,0表示水平顯示刻度標籤
width = 0.8, title = '近兩年5個城市億萬資產家庭數比較')
# 新增y軸標籤
plt.ylabel('億萬資產家庭數')
plt.xlabel('')
plt.show()

# seaborn模組之垂直或水平條形圖
# 匯入第三方模組
import seaborn as sns

sns.barplot(y = 'Province', # 指定條形圖x軸的資料
x = 'GDP', # 指定條形圖y軸的資料
data = GDP, # 指定需要繪圖的資料集
color = 'steelblue', # 指定條形圖的填充色
orient = 'horizontal' # 將條形圖水平顯示
)
# 重新設定x軸和y軸的標籤
plt.xlabel('GDP(萬億)')
plt.ylabel('')
# 新增圖形的標題
plt.title('2017年度6個省份GDP分佈')
# 為每個條形圖新增數值標籤
for y,x in enumerate(GDP.GDP):
plt.text(x,y,'%s' %round(x,1),va='center')
# 顯示圖形
plt.show()

# 讀入資料
Titanic = pd.read_csv(r'F:\\python_Data_analysis_and_mining\\06\\titanic_train.csv')
print(Titanic.shape)
# 繪製水平交錯條形圖
sns.barplot(x = 'Pclass', # 指定x軸資料
y = 'Age', # 指定y軸資料
hue = 'Sex', # 指定分組資料
data = Titanic, # 指定繪圖資料集
palette = 'RdBu', # 指定男女性別的不同顏色
errcolor = 'blue', # 指定誤差棒的顏色
errwidth=2, # 指定誤差棒的線寬
saturation = 1, # 指定顏色的透明度,這裡設定為無透明度
capsize = 0.05 # 指定誤差棒兩端線條的寬度
)
# 新增圖形標題
plt.title('各船艙等級中男女乘客的年齡差異')
# 顯示圖形
plt.show()

# 讀入資料
Titanic = pd.read_csv(r'F:\\python_Data_analysis_and_mining\\06\\titanic_train.csv')
# matplotlib模組繪製直方圖
# 檢查年齡是否有缺失
print(any(Titanic.Age.isnull()))
# 不妨刪除含有缺失年齡的觀察
Titanic.dropna(subset=['Age'], inplace=True)
# 繪製直方圖
plt.hist(x = Titanic.Age, # 指定繪圖資料
bins = 20, # 指定直方圖中條塊的個數
color = 'steelblue', # 指定直方圖的填充色
edgecolor = 'black' # 指定直方圖的邊框色
)
# 新增x軸和y軸標籤
plt.xlabel('年齡')
plt.ylabel('頻數')
# 新增標題
plt.title('乘客年齡分佈')
# 顯示圖形
plt.show()

# Pandas模組繪製直方圖和核密度圖
# 繪製直方圖
Titanic.Age.plot(kind = 'hist', bins = 20, color = 'steelblue', edgecolor = 'black', normed = True, label = '直方圖')
# 繪製核密度圖
Titanic.Age.plot(kind = 'kde', color = 'red', label = '核密度圖')
# 新增x軸和y軸標籤
plt.xlabel('年齡')
plt.ylabel('核密度值')
# 新增標題
plt.title('乘客年齡分佈')
# 顯示圖例
plt.legend()
# 顯示圖形
plt.show()

# seaborn模組繪製分組的直方圖和核密度圖
# 取出男性年齡
Age_Male = Titanic.Age[Titanic.Sex == 'male']
# 取出女性年齡
Age_Female = Titanic.Age[Titanic.Sex == 'female']

# 繪製男女乘客年齡的直方圖
sns.distplot(Age_Male, bins = 20, kde = False, hist_kws = {'color':'steelblue'}, label = '男性')
# 繪製女性年齡的直方圖
sns.distplot(Age_Female, bins = 20, kde = False, hist_kws = {'color':'purple'}, label = '女性')
plt.title('男女乘客的年齡直方圖')
# 顯示圖例
plt.legend()
# 顯示圖形
plt.show()

# 繪製男女乘客年齡的核密度圖
sns.distplot(Age_Male, hist = False, kde_kws = {'color':'red', 'linestyle':'-'},
norm_hist = True, label = '男性')
# 繪製女性年齡的核密度圖
sns.distplot(Age_Female, hist = False, kde_kws = {'color':'black', 'linestyle':'--'},
norm_hist = True, label = '女性')
plt.title('男女乘客的年齡核密度圖')
# 顯示圖例
plt.legend()
# 顯示圖形
plt.show()

import pandas as pd
import matplotlib.pyplot as plt

# 讀取資料
Sec_Buildings = pd.read_excel(r'F:\\python_Data_analysis_and_mining\\06\\sec_buildings.xlsx')
print(Sec_Buildings.shape)
# 繪製箱線圖
plt.boxplot(x = Sec_Buildings.price_unit, # 指定繪圖資料
patch_artist=True, # 要求用自定義顏色填充盒形圖,預設白色填充
showmeans=True, # 以點的形式顯示均值
boxprops = {'color':'black','facecolor':'steelblue'}, # 設定箱體屬性,如邊框色和填充色
# 設定異常點屬性,如點的形狀、填充色和點的大小
flierprops = {'marker':'o','markerfacecolor':'red', 'markersize':3},
# 設定均值點的屬性,如點的形狀、填充色和點的大小
meanprops = {'marker':'D','markerfacecolor':'indianred', 'markersize':4},
# 設定中位數線的屬性,如線的型別和顏色
medianprops = {'linestyle':'--','color':'orange'},
labels = [''] # 刪除x軸的刻度標籤,否則圖形顯示刻度標籤為1
)
# 新增圖形標題
plt.title('二手房單價分佈的箱線圖')
# 顯示圖形
plt.show()

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 讀取資料
Sec_Buildings = pd.read_excel(r'F:\\python_Data_analysis_and_mining\\06\\sec_buildings.xlsx')
print(Sec_Buildings.shape)
# 二手房在各行政區域的平均單價
group_region = Sec_Buildings.groupby('region')
print(group_region)
avg_price = group_region.aggregate({'price_unit':np.mean}).sort_values('price_unit', ascending = False)
print(avg_price)
# 通過迴圈,將不同行政區域的二手房儲存到列表中
region_price = []
for region in avg_price.index:
region_price.append(Sec_Buildings.price_unit[Sec_Buildings.region == region])
# print(region_price)
# 繪製分組箱線圖
plt.boxplot(x = region_price,
patch_artist=True,
labels = avg_price.index, # 新增x軸的刻度標籤
showmeans=True,
boxprops = {'color':'black', 'facecolor':'steelblue'},
flierprops = {'marker':'o','markerfacecolor':'red', 'markersize':3},
meanprops = {'marker':'D','markerfacecolor':'indianred', 'markersize':4},
medianprops = {'linestyle':'--','color':'orange'}
)
# 新增y軸標籤
plt.ylabel('單價(元)')
# 新增標題
plt.title('不同行政區域的二手房單價對比')
# 顯示圖形
plt.show()

 

 

import seaborn as sns

# 繪製分組箱線圖
sns.boxplot(x = 'region', y = 'price_unit', data = Sec_Buildings,
order = avg_price.index, showmeans=True,color = 'steelblue',
flierprops = {'marker':'o','markerfacecolor':'red', 'markersize':3},
meanprops = {'marker':'D','markerfacecolor':'indianred', 'markersize':4},
medianprops = {'linestyle':'--','color':'orange'}
)
# 更改x軸和y軸標籤
plt.xlabel('')
plt.ylabel('單價(元)')
# 新增標題
plt.title('不同行政區域的二手房單價對比')
# 顯示圖形
plt.show()

# 讀取資料
tips = pd.read_csv(r'F:\\python_Data_analysis_and_mining\\06\\tips.csv')
print(tips.shape)
# 繪製分組小提琴圖
sns.violinplot(x = "total_bill", # 指定x軸的資料
y = "day", # 指定y軸的資料
hue = "sex", # 指定分組變數
data = tips, # 指定繪圖的資料集
order = ['Thur','Fri','Sat','Sun'], # 指定x軸刻度標籤的順序
scale = 'count', # 以男女客戶數調節小提琴圖左右的寬度
split = True, # 將小提琴圖從中間割裂開,形成不同的密度曲線;
palette = 'RdBu' # 指定不同性別對應的顏色(因為hue引數為設定為性別變數)
)
# 新增圖形標題
plt.title('每天不同性別客戶的消費額情況')
# 設定圖例
plt.legend(loc = 'upper center', ncol = 2)
# 顯示圖形
plt.show()

# 資料讀取
wechat = pd.read_excel(r'F:\\python_Data_analysis_and_mining\\06\\wechat.xlsx')
print(wechat.shape)
# 繪製單條折線圖
plt.plot(wechat.Date, # x軸資料
wechat.Counts, # y軸資料
linestyle = '-', # 折線型別
linewidth = 2, # 折線寬度
color = 'steelblue', # 折線顏色
marker = 'o', # 折線圖中新增圓點
markersize = 6, # 點的大小
markeredgecolor='black', # 點的邊框色
markerfacecolor='brown') # 點的填充色
# 新增y軸標籤
plt.ylabel('人數')
# 新增圖形標題
plt.title('每天微信文章閱讀人數趨勢')
# 顯示圖形
plt.show()

# 繪製兩條折線圖
# 匯入模組,用於日期刻度的修改
import matplotlib as mpl

# 繪製閱讀人數折線圖
plt.plot(wechat.Date, # x軸資料
wechat.Counts, # y軸資料
linestyle = '-', # 折線型別,實心線
color = 'steelblue', # 折線顏色
label = '閱讀人數'
)
# 繪製閱讀人次折線圖
plt.plot(wechat.Date, # x軸資料
wechat.Times, # y軸資料
linestyle = '--', # 折線型別,虛線
color = 'indianred', # 折線顏色
label = '閱讀人次'
)
plt.show()

import matplotlib as mpl

# 獲取圖的座標資訊
ax = plt.gca()
# 設定日期的顯示格式
date_format = mpl.dates.DateFormatter("%m-%d")
ax.xaxis.set_major_formatter(date_format)
# 設定x軸顯示多少個日期刻度
# xlocator = mpl.ticker.LinearLocator(10)
# 設定x軸每個刻度的間隔天數
xlocator = mpl.ticker.MultipleLocator(7)
ax.xaxis.set_major_locator(xlocator)
# 為了避免x軸刻度標籤的緊湊,將刻度標籤旋轉45度
plt.xticks(rotation=45)

# 新增y軸標籤
plt.ylabel('人數')
# 新增圖形標題
plt.title('每天微信文章閱讀人數與人次趨勢')
# 新增圖例
plt.legend()
# 顯示圖形
plt.show()

# 讀取天氣資料
weather = pd.read_excel(r'F:\\python_Data_analysis_and_mining\\06\\weather.xlsx')
# 統計每月的平均最高氣溫
data = weather.pivot_table(index = 'month', columns='year', values='high')
# 繪製折線圖
data.plot(kind = 'line',
style = ['-','--',':'] # 設定折線圖的線條型別
)
# 修改x軸和y軸標籤
plt.xlabel('月份')
plt.ylabel('氣溫')
# 新增圖形標題
plt.title('每月平均最高氣溫波動趨勢')
# 顯示圖形
plt.show()

# 讀入資料
iris = pd.read_csv(r'F:\\python_Data_analysis_and_mining\\06\\iris.csv')
print(iris.shape)
# 繪製散點圖
plt.scatter(x = iris.Petal_Width, # 指定散點圖的x軸資料
y = iris.Petal_Length, # 指定散點圖的y軸資料
color = 'steelblue' # 指定散點圖中點的顏色
)
# 新增x軸和y軸標籤
plt.xlabel('花瓣寬度')
plt.ylabel('花瓣長度')
# 新增標題
plt.title('鳶尾花的花瓣寬度與長度關係')
# 顯示圖形
plt.show()

# Pandas模組繪製散點圖
# 繪製散點圖
iris.plot(x = 'Petal_Width', y = 'Petal_Length', kind = 'scatter', title = '鳶尾花的花瓣寬度與長度關係')
# 修改x軸和y軸標籤
plt.xlabel('花瓣寬度')
plt.ylabel('花瓣長度')
# 顯示圖形
plt.show()

# seaborn模組繪製分組散點圖
sns.lmplot(x = 'Petal_Width', # 指定x軸變數
y = 'Petal_Length', # 指定y軸變數
hue = 'Species', # 指定分組變數
data = iris, # 指定繪圖資料集
legend_out = False, # 將圖例呈現在圖框內
truncate=True # 根據實際的資料範圍,對擬合線作截斷操作
)
# 修改x軸和y軸標籤
plt.xlabel('花瓣寬度')
plt.ylabel('花瓣長度')
# 新增標題
plt.title('鳶尾花的花瓣寬度與長度關係')
# 顯示圖形
plt.show()

# 讀取資料
Prod_Category = pd.read_excel(r'F:\\python_Data_analysis_and_mining\\06\\SuperMarket.xlsx')
print(Prod_Category.shape)
# 將利潤率標準化到[0,1]之間(因為利潤率中有負數),然後加上微小的數值0.001
range_diff = Prod_Category.Profit_Ratio.max()-Prod_Category.Profit_Ratio.min()
print(range_diff)
Prod_Category['std_ratio'] = (Prod_Category.Profit_Ratio-Prod_Category.Profit_Ratio.min())/range_diff + 0.001
print(Prod_Category)
# 繪製辦公用品的氣泡圖
plt.scatter(x = Prod_Category.Sales[Prod_Category.Category == '辦公用品'],
y = Prod_Category.Profit[Prod_Category.Category == '辦公用品'],
s = Prod_Category.std_ratio[Prod_Category.Category == '辦公用品']*1000,
color = 'steelblue', label = '辦公用品', alpha = 0.6
)
# 繪製技術產品的氣泡圖
plt.scatter(x = Prod_Category.Sales[Prod_Category.Category == '技術產品'],
y = Prod_Category.Profit[Prod_Category.Category == '技術產品'],
s = Prod_Category.std_ratio[Prod_Category.Category == '技術產品']*1000,
color = 'indianred' , label = '技術產品', alpha = 0.6
)
# 繪製傢俱產品的氣泡圖
plt.scatter(x = Prod_Category.Sales[Prod_Category.Category == '傢俱產品'],
y = Prod_Category.Profit[Prod_Category.Category == '傢俱產品'],
s = Prod_Category.std_ratio[Prod_Category.Category == '傢俱產品']*1000,
color = 'black' , label = '傢俱產品', alpha = 0.6
)
# 新增x軸和y軸標籤
plt.xlabel('銷售額')
plt.ylabel('利潤')
# 新增標題
plt.title('銷售額、利潤及利潤率的氣泡圖')
# 新增圖例
plt.legend()
# 顯示圖形
plt.show()

# 讀取資料
Sales = pd.read_excel(r'F:\\python_Data_analysis_and_mining\\06\\Sales.xlsx')
print(Sales.shape)
print(Sales.head())
# 根據交易日期,衍生出年份和月份欄位
Sales['year'] = Sales.Date.dt.year
Sales['month'] = Sales.Date.dt.month
print(Sales.head())
# 統計每年各月份的銷售總額
Summary = Sales.pivot_table(index = 'month', columns = 'year', values = 'Sales', aggfunc = np.sum)
print(Summary)
# 繪製熱力圖
sns.heatmap(data = Summary, # 指定繪圖資料
cmap = 'PuBuGn', # 指定填充色
linewidths = .1, # 設定每個單元格邊框的寬度
annot = True, # 顯示數值
fmt = '.1e' # 以科學計演算法顯示資料
)
#新增標題
plt.title('每年各月份銷售總額熱力圖')
# 顯示圖形
plt.show()

# 讀取資料
Prod_Trade = pd.read_excel(r'F:\\python_Data_analysis_and_mining\\06\\Prod_Trade.xlsx')
print(Prod_Trade.shape)
print(Prod_Trade.head())
# 衍生出交易年份和月份欄位
Prod_Trade['year'] = Prod_Trade.Date.dt.year
Prod_Trade['month'] = Prod_Trade.Date.dt.month
print(Prod_Trade.head())
# 設定大圖框的長和高
plt.figure(figsize = (12,6))
# 設定第一個子圖的佈局
ax1 = plt.subplot2grid(shape = (2,3), loc = (0,0))
# 統計2012年各訂單等級的數量
Class_Counts = Prod_Trade.Order_Class[Prod_Trade.year == 2012].value_counts()
Class_Percent = Class_Counts/Class_Counts.sum()
# 將餅圖設定為圓形(否則有點像橢圓)
ax1.set_aspect(aspect = 'equal')
# 繪製訂單等級餅圖
ax1.pie(x = Class_Percent.values, labels = Class_Percent.index, autopct = '%.1f%%')
# 新增標題
ax1.set_title('各等級訂單比例')

# 設定第二個子圖的佈局
ax2 = plt.subplot2grid(shape = (2,3), loc = (0,1))
# 統計2012年每月銷售額
Month_Sales = Prod_Trade[Prod_Trade.year == 2012].groupby(by = 'month').aggregate({'Sales':np.sum})
# 繪製銷售額趨勢圖
Month_Sales.plot(title = '2012年各月銷售趨勢', ax = ax2, legend = False)
# 刪除x軸標籤
ax2.set_xlabel('')

# 設定第三個子圖的佈局
ax3 = plt.subplot2grid(shape = (2,3), loc = (0,2), rowspan = 2)
# 繪製各運輸方式的成本箱線圖
sns.boxplot(x = 'Transport', y = 'Trans_Cost', data = Prod_Trade, ax = ax3)
# 新增標題
ax3.set_title('各運輸方式成本分佈')
# 刪除x軸標籤
ax3.set_xlabel('')
# 修改y軸標籤
ax3.set_ylabel('運輸成本')

# 設定第四個子圖的佈局
ax4 = plt.subplot2grid(shape = (2,3), loc = (1,0), colspan = 2)
# 2012年客單價分佈直方圖
sns.distplot(Prod_Trade.Sales[Prod_Trade.year == 2012], bins = 40, norm_hist = True, ax = ax4, hist_kws = {'color':'steelblue'}, kde_kws=({'linestyle':'--', 'color':'red'}))
# 新增標題
ax4.set_title('2012年客單價分佈圖')
# 修改x軸標籤
ax4.set_xlabel('銷售額')

# 調整子圖之間的水平間距和高度間距
plt.subplots_adjust(hspace=0.6, wspace=0.3)
# 圖形顯示
plt.show()