Python各模塊:matplotlib、pandas、seaborn、plotly_express、pyecharts可視化方法大全整合(更新中...)


內容持續更新中…

對博客《python常見圖形代碼可視化大全整理(包括動圖)更新中…》的另一種排版,感覺查找和整理更方便一點吧。


警告信息和可視化時中文和負號的正常顯示

import matplotlib as mpl
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")   # 忽略警告信息輸出

# mpl.style.use('ggplot')

# 爲了畫圖中文可以正常顯示
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] #指定默認字體
plt.rcParams['axes.unicode_minus'] = False  #解決保存圖像時負號'-'顯示爲方塊的問題

一、matplotlib模塊

1 餅圖

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

# 構造數據
edu = [0.2515,0.3724,0.3336,0.0368,0.0057]
labels = ['中專','大專','本科','碩士','其他']

# 繪製餅圖
plt.pie(x = edu, # 繪圖數據
        labels=labels, # 添加教育水平標籤
        autopct='%.1f%%' # 設置百分比的格式,這裏保留一位小數
       )
# 添加圖標題
plt.title('失信用戶的教育水平分佈')
# 顯示圖形
plt.show()

在這裏插入圖片描述

# 添加修飾的餅圖 
explode = [0,0.1,0,0,0]  # 生成數據,用於突出顯示大專學歷人羣
colors=['#9999ff','#ff9999','#7777aa','#2442aa','#dd5555']  # 自定義顏色

# 將橫、縱座標軸標準化處理,確保餅圖是一個正圓,否則爲橢圓
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()

在這裏插入圖片描述

2 條形圖

2.1 垂直或水平條形圖

# 條形圖的繪製--垂直條形圖
# 讀入數據
GDP = pd.read_excel(r'Province GDP 2017.xlsx')
# 設置繪圖風格(不妨使用R語言中的ggplot2風格)
plt.style.use('ggplot')
# 繪製條形圖
plt.bar(x = 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(y = 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()

在這裏插入圖片描述

2.2 堆疊條形圖

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

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

在這裏插入圖片描述

2.3 水平交錯條形圖

# 條形圖的繪製--水平交錯條形圖
# 導入第三方模塊
import numpy as np
# 讀入數據
HuRun = pd.read_excel(r'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(x = np.arange(len(Cities)), height = Counts2016, label = '2016', color = 'steelblue', width = bar_width)
plt.bar(x = np.arange(len(Cities))+bar_width, height = Counts2017, label = '2017', color = 'indianred', width = bar_width)
# 添加刻度標籤(向右偏移0.225)
plt.xticks(np.arange(len(Cities))+0.2, Cities)
# 添加y軸標籤
plt.ylabel('億萬資產家庭數')
# 添加圖形標題
plt.title('近兩年5個城市億萬資產家庭數比較')
# 添加圖例
plt.legend()
# 顯示圖形
plt.show()

在這裏插入圖片描述

3 直方圖

# matplotlib模塊繪製直方圖
# 檢查年齡是否有缺失
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()

在這裏插入圖片描述

4 箱線圖

4.1 單個箱線圖

# 讀取數據
Sec_Buildings = pd.read_excel(r'sec_buildings.xlsx')
# 繪製箱線圖
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()

在這裏插入圖片描述

4.2 分組箱線圖

# 二手房在各行政區域的平均單價
group_region = Sec_Buildings.groupby('region')
avg_price = group_region.aggregate({'price_unit':np.mean}).sort_values('price_unit', ascending = False)

# 通過循環,將不同行政區域的二手房存儲到列表中
region_price = []
for region in avg_price.index:
    region_price.append(Sec_Buildings.price_unit[Sec_Buildings.region == region])
# 繪製分組箱線圖
plt.figure(figsize=(10,5))
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()

在這裏插入圖片描述
注意

  • 用matplotlib模塊繪製如上所示的分組箱線圖會相對煩瑣一些,由於boxplot函數每次只能繪製一個箱線圖,爲了能夠實現多個箱線圖的繪製,對數據稍微做了一些變動;
  • pandas模塊中的plot方法可以繪製分組箱線圖,但是該方法是基於數據框執行的,並且數據框的每一列對應一個箱線圖。對於二手房數據集來說,應用plot方法繪製分組箱線圖不太合適,因爲每一個行政區的二手房數量不一致,將導致無法重構一個新的數據框用於繪圖。

5 折線圖

5.1 單條折線圖

# 數據讀取
wechat = pd.read_excel(r'wechat.xlsx')
# 繪製單條折線圖
plt.figure(figsize=(10,5))
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()

在這裏插入圖片描述

5.2 兩條折線圖

# 繪製兩條折線圖
# 導入模塊,用於日期刻度的修改
import matplotlib as mpl
# 繪製閱讀人數折線圖
plt.figure(figsize=(10,5))
plt.plot(wechat.Date, # x軸數據
         wechat.Counts, # y軸數據
         linestyle = '-', # 折線類型,實心線
         color = 'steelblue', # 折線顏色
         label = '閱讀人數'
         )
# 繪製閱讀人次折線圖
plt.plot(wechat.Date, # x軸數據
         wechat.Times, # y軸數據
         linestyle = '--', # 折線類型,虛線
         color = 'indianred', # 折線顏色
         label = '閱讀人次'
         )

# 獲取圖的座標信息
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()

在這裏插入圖片描述

6 散點圖

散點圖用於發現兩個數值變量之間的關係。

# 讀入數據
iris = pd.read_csv(r'iris.csv')
# 繪製散點圖
plt.scatter(x = iris.Petal_Width, # 指定散點圖的x軸數據
            y = iris.Petal_Length, # 指定散點圖的y軸數據
            color = 'steelblue' # 指定散點圖中點的顏色
           )
# 添加x軸和y軸標籤
plt.xlabel('花瓣寬度')
plt.ylabel('花瓣長度')
# 添加標題
plt.title('鳶尾花的花瓣寬度與長度關係')
# 顯示圖形
plt.show()

在這裏插入圖片描述

7 氣泡圖

氣泡圖可以展現三個數值變量之間的關係。
注意:pandas模塊和seaborn模塊中沒有繪製氣泡圖的方法或函數。另外,可以使用Python的bokeh模塊,來繪製氣泡圖。

# 讀取數據
Prod_Category = pd.read_excel(r'SuperMarket.xlsx')
# 將利潤率標準化到[0,1]之間(因爲利潤率中有負數),然後加上微小的數值0.001
range_diff = Prod_Category.Profit_Ratio.max()-Prod_Category.Profit_Ratio.min()
Prod_Category['std_ratio'] = (Prod_Category.Profit_Ratio-Prod_Category.Profit_Ratio.min())/range_diff + 0.001

plt.figure(figsize=(10,5))
# 繪製辦公用品的氣泡圖
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()

在這裏插入圖片描述

8 競賽條形圖

# 導入所需模塊
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.animation as animation
from IPython.display import HTML

# 讀取數據
df = pd.read_csv('country_data.csv',usecols=['name', 'group', 'year', 'value'])
df.head(3)

# 配置不同洲的顏色
colors = dict(zip(
    ['India', 'Europe', 'Asia', 'Latin America',
     'Middle East', 'North America', 'Africa'],
    ['#adb0ff', '#ffb3ff', '#90d595', '#e48381',
     '#aafbff', '#f7bb5f', '#eafb50']
))
# 國家和對應的洲,化爲字典
group_lk = df.set_index('name')['group'].to_dict()

def draw_barchart(year):
    dff = df[df['year'].eq(year)].sort_values(by='value', ascending=True).tail(10)
    ax.clear()
    ax.barh(dff['name'], dff['value'], color=[colors[group_lk[x]] for x in dff['name']])
    dx = dff['value'].max() / 200
    for i, (value, name) in enumerate(zip(dff['value'], dff['name'])):
        ax.text(value-dx, i,     name,           size=14, weight=600, ha='right', va='bottom')
        ax.text(value-dx, i-.25, group_lk[name], size=10, color='#444444', ha='right', va='baseline')
        ax.text(value+dx, i,     f'{value:,.0f}',  size=14, ha='left',  va='center')
    # ... polished styles
    ax.text(1, 0.4, year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800)
    ax.text(0, 1.06, 'Population (thousands)', transform=ax.transAxes, size=12, color='#777777')
    ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
    ax.xaxis.set_ticks_position('top')
    ax.tick_params(axis='x', colors='#777777', labelsize=12)
    ax.set_yticks([])
    ax.margins(0, 0.01)
    ax.grid(which='major', axis='x', linestyle='-')
    ax.set_axisbelow(True)
    ax.text(0, 1.12, 'The most populous cities in the world from 1500 to 2018',
            transform=ax.transAxes, size=24, weight=600, ha='left')
    ax.text(1, 0, 'by @pratapvardhan; credit @jburnmurdoch', transform=ax.transAxes, ha='right',
            color='#777777', bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
    plt.box(False)

#plt.xkcd()
fig, ax = plt.subplots(figsize=(15, 8))
animator = animation.FuncAnimation(fig, draw_barchart, frames=range(1900, 2019))
HTML(animator.to_jshtml()) 

在這裏插入圖片描述
在這裏插入圖片描述

二、panda模塊

1 餅圖

# 導入第三方模塊
import pandas as pd
# 構建序列
data1 = pd.Series({'中專':0.2515,'大專':0.3724,'本科':0.3336,'碩士':0.0368,'其他':0.0057})
# 將序列的名稱設置爲空字符,否則繪製的餅圖左邊會出現None這樣的字眼
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()

在這裏插入圖片描述

2 條形圖

2.1 垂直條形圖

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

在這裏插入圖片描述

2.2 水平交錯條形圖

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

在這裏插入圖片描述

3 直方圖與核密度曲線

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

在這裏插入圖片描述

4 分組折線圖

數據框的pivot_table方法,形成一張滿足條件的透視表。

# 讀取天氣數據
weather = pd.read_excel(r'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()

在這裏插入圖片描述

5 散點圖

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

在這裏插入圖片描述

三、seaborn模塊

1 條形圖

1.1 水平條形圖

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

在這裏插入圖片描述

1.2 水平交錯條形圖

# 讀入數據
Titanic = pd.read_csv(r'titanic_train.csv')
# 繪製水平交錯條形圖
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並非彙總好的數據,是不可以直接應用到matplotlib模塊中的bar函數與pandas模塊中的plot方法。如需使用,必須先對數據集進行分組聚合。

2 可分組的直方圖與核密度曲線

# seaborn模塊繪製分組的直方圖和核密度圖
# 取出男性年齡
Age_Male = Titanic.Age[Titanic.Sex == 'male']
# 取出女性年齡
Age_Female = Titanic.Age[Titanic.Sex == 'female']
plt.figure(figsize=(15,5))
plt.subplot(121)

# 繪製男女乘客年齡的直方圖
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()

plt.subplot(122)
# 繪製男女乘客年齡的核密度圖
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()

在這裏插入圖片描述

3 分組箱線圖

# 繪製分組箱線圖
plt.figure(figsize=(10,5))
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()

在這裏插入圖片描述

4 分組小提琴圖

# 讀取數據
tips = pd.read_csv(r'tips.csv')
# 繪製分組小提琴圖
sns.violinplot(y = "total_bill", # 指定y軸的數據
               x = "day", # 指定x軸的數據
               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()

在這裏插入圖片描述

5 散點圖

lmplot函數不僅可以繪製分組散點圖,還可以對每個組內的散點添加迴歸線(默認擬合線性迴歸線)。分組效果的體現是通過hue參數設置的,如果需要擬合其他迴歸線,可以指定:

  • lowess參數(局部多項式迴歸)
  • logistic參數(邏輯迴歸)
  • order參數(多項式迴歸)
  • robust參數(魯棒迴歸)
# 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()

在這裏插入圖片描述

6 熱力圖

熱力圖則體現了兩個離散變量之間的組合關係。
有時也稱之爲交叉填充表。該圖形最典型的用法就是實現列聯表的可視化,即通過圖形的方式展現兩個離散變量之間的組合關係。

# 讀取數據
Sales = pd.read_excel(r'Sales.xlsx')
# 根據交易日期,衍生出年份和月份字段
Sales['year'] = Sales.Date.dt.year
Sales['month'] = Sales.Date.dt.month
# 統計每年各月份的銷售總額
Summary = Sales.pivot_table(index = 'month', columns = 'year', values = 'Sales', aggfunc = np.sum)

# 繪製熱力圖
sns.heatmap(data = Summary, # 指定繪圖數據
            cmap = 'PuBuGn', # 指定填充色
            linewidths = .1, # 設置每個單元格邊框的寬度
            annot = True, # 顯示數值
            fmt = '.1e' # 以科學計算法顯示數據
            )
#添加標題
plt.title('每年各月份銷售總額熱力圖')
# 顯示圖形
plt.show()

在這裏插入圖片描述

四、儀表板

將繪製的多個圖形組合到一個大圖框內,形成類似儀表板的效果。
多種圖形的組合,可以使用matplotlib模塊中的subplot2grid函數

# 讀取數據
Prod_Trade = pd.read_excel(r'Prod_Trade.xlsx')
# 衍生出交易年份和月份字段
Prod_Trade['year'] = Prod_Trade.Date.dt.year
Prod_Trade['month'] = Prod_Trade.Date.dt.month

# 設置大圖框的長和高
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()

在這裏插入圖片描述
注意:

  • 在繪製每一幅子圖之前,都需要運用subplot2grid函數控制子圖的位置,並傳遞給一個變量對象(如代碼中的ax1、ax2等);
  • 如果通過matplotlib模塊繪製子圖,則必須使用ax1.plot_function的代碼語法(如上代碼中,繪製餅圖的過程);
  • 如果通過pandas模塊或seaborn模塊繪製子圖,則需要爲繪圖“方法”或函數指定ax參數(如上代碼中,繪製折線圖、直方圖和箱線圖的過程);
  • 如果爲子圖添加標題、座標軸標籤、刻度值標籤等,不能直接使用plt.title、plt.xlabel、plt.xticks等函數,而是換成ax1.set_*的形式(可參考如上代碼中對子圖標題、座標軸標籤的設置);
  • 通過subplots_adjust函數重新修改子圖之間的水平間距和垂直間距。1

五、plotly_express庫可視化

一個強大的可視化庫plotly_express(參考博文2,3 )可以在一個函數調用中創建豐富的交互式繪圖,包括分面繪圖(faceting)、地圖、動畫和趨勢線。 它帶有數據集、顏色面板和主題
Plotly Express 完全免費。安裝:

pip install plotly_express

大多數繪圖只需要一個函數調用,接受一個整潔的DataFrame

1 散點圖

以下是內置的 Gapminder 數據集的示例,顯示2007年按國家/地區的人均預期壽命和人均GDP 之間的趨勢。示例數據如下:
數據示例

# 加載模塊
import plotly_express as px 
gm = px.data.gapminder() # 數據框格式
# print('數據的前3行示例:\n',gm.head(3))

# 篩選出2007年的數據
gm2007 = gm.query('year==2007') 
px.scatter(gm2007,x='gdpPercap',y='lifeExp')

在這裏插入圖片描述
可以使用 color 參數爲不同類別的點着色。

# 着色
px.scatter(gm2007,x='gdpPercap',y='lifeExp',color='continent')

在這裏插入圖片描述

2 氣泡圖

通過國家的人口數量顯示點的大小,參數size來設置。

# 加上點大小設置
px.scatter(gm2007,x='gdpPercap',y='lifeExp',color='continent',size='pop',size_max=50)

在這裏插入圖片描述
添加一個 參數hover_name ,可以輕鬆識別任何一點。

# 加上hover_name參數
px.scatter(gm2007,x='gdpPercap',y='lifeExp',color='continent',size='pop',size_max=50,hover_name='country')

在這裏插入圖片描述

3 分組-標色-氣泡圖

自己起的名字,通過參數facet_col =“continent” 可以將各大洲區分開。讓x軸取對數(log_x)以便我們在圖表中看的更清晰。

# 再加上facet_col參數
px.scatter(gm2007,x='gdpPercap',y='lifeExp',color='continent',size='pop',size_max=50,
           hover_name='country',facet_col='continent',log_x=True)

在這裏插入圖片描述

4 氣泡動圖

可以通過設置 animation_frame=“year” 來設置動畫。

# 再加上animation_frame參數,來設置動畫 ,爲了圖表更美觀一點,對做座標軸進行一些調整
px.scatter(gm,x='gdpPercap',y='lifeExp',color='continent',size='pop',size_max=50,
           hover_name='country',animation_frame='year',log_x=True,range_x=[100,100000],
           range_y=[25,90],labels=dict(pop='population',gdpPercap='GDP per Capita',lifeExp='Life Expectancy'))

在這裏插入圖片描述

5 結果保存爲html和圖片

import plotly_express as px
import plotly

pyplt=plotly.offline
#plotly.offline.init_notebook_mode()
# pyplt.init_notebook_mode()

# 再加上animation_frame參數,來設置動畫 ,爲了圖表更美觀一點,對做座標軸進行一些調整
fig = px.scatter(gm,x='gdpPercap',y='lifeExp',color='continent',size='pop',size_max=50,
           hover_name='country',animation_frame='year',log_x=True,range_x=[100,100000],
           range_y=[25,90],labels=dict(pop='population',gdpPercap='GDP per Capita',lifeExp='Life Expectancy'))
#
# data = fig.to_html()
pyplt.plot(fig,filename='tmp/demo',show_link=True,image='png')

六、pyecharts模塊

參考內容 pyecharts官方文檔4 和pyecharts-gallery5
看到的比較有趣的學習內容:

  • 【蠟燭圖6
  • pyecharts可視化結果分類展示 7

支持 selenium/phantomjs 渲染圖片

非必須,如果無此需求的開發者可忽略,並不會影響正常的使用。

pyecharts v1 提供兩種模式渲染圖片,selenium 和 phantomjs,分別需要安裝 snapshot-selenium 和 snapshot-phantomjs。

from pyecharts.charts import Bar
from pyecharts.globals import CurrentConfig, NotebookType, OnlineHostType
# CurrentConfig.ONLINE_HOST = "https://www.echartsjs.com/examples/vendors/echarts/"
CurrentConfig.ONLINE_HOST = "https://assets.pyecharts.org/assets/"

bar = Bar()
bar.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"])
bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
bar.render_notebook()

在這裏插入圖片描述

from pyecharts.faker import Faker
from pyecharts import options as opts
from pyecharts.charts import EffectScatter
from pyecharts.globals import SymbolType

def effectscatter_base() -> EffectScatter:
    c = (
        EffectScatter()
        .add_xaxis(Faker.choose())
        .add_yaxis("", Faker.values())
        .set_global_opts(title_opts=opts.TitleOpts(title="EffectScatter-基本示例"))
    )
    return c
effectscatter_base().render_notebook()

在這裏插入圖片描述

from pyecharts import options as opts
from pyecharts.charts import Map
from pyecharts.faker import Faker

NAME_MAP_DATA = {'Canada':'加拿大'}
c = (
    Map(init_opts = opts.InitOpts(width="500px",
                                  height="300px",
                                  bg_color="steelblue"
                                 )
       )
    .add("", [list(z) for z in zip(Faker.country, Faker.values())], "world",is_roam=False,name_map=NAME_MAP_DATA)
    .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Map-世界地圖"),
        visualmap_opts=opts.VisualMapOpts(max_=200,
                                         range_text=['high','low']),
        toolbox_opts = opts.ToolboxOpts(orient='vertical',
                                       pos_left="93%"),
        brush_opts = opts.BrushOpts(brush_type=['lineX'],
                                   brush_style={"borderWidth": 1,
                                               "color": "rgba(10,160,180,0.4)",
                                               "borderColor": "rgba(120,140,180,0.8)"
                                               }
                                   )
    )
)
c.render_notebook()

在這裏插入圖片描述

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')
# 導入pyecharts庫
from pyecharts.charts import Bar,Timeline
import pyecharts.options as opts
from pyecharts.commons.utils import JsCode

color_function = """
        function(params) {
                var colorList = [
                        '#C1232B','#B5C334','#FCCE10','#E87C25','#27727B',
                        '#FE8463','#9BCA63','#FAD860','#F3A43B','#60C0DD',
                        '#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0',
                        '#FAD260','#C2E579'
                    ];
                return colorList[params.dataIndex]
                }
              """   

timeline = Timeline(init_opts=opts.InitOpts(
                                           width='1000px',
                                           height='500px'
                                           )
                   )
timeline.add_schema(is_auto_play = True, 
                    is_loop_play = True,
                    pos_left = 'left',
                    play_interval = 300,
#                     is_timeline_show=False
                   )

for column in gdp.columns:
    data = gdp[column].sort_values()
    bar_y = list(data.index)
    bar_x = [int(i) for i in data]
    
    bar = (
        Bar()
        .add_xaxis(bar_y)
        .reversal_axis()
        .add_yaxis(
            '',
            bar_x,
            itemstyle_opts=opts.ItemStyleOpts(color= JsCode(color_function)))
        .set_global_opts(title_opts = opts.TitleOpts(title='全市各區縣GDP數據'),
                         
#                         datazoom_opts=opts.DataZoomOpts(type_='inside'), #slider
#                          visualmap_opts=opts.VisualMapOpts(min_ = min(bar_x),
#                                                            max_ = max(bar_x),
#                                                            pos_left='right',
#                                                            orient='horizontal'
                                                          )
#                         )
        .set_series_opts(label_opts=opts.LabelOpts(position='right'), )
    )
    timeline.add(bar,"%s年"%column)
    
timeline.render_notebook()

在這裏插入圖片描述

正確顯示中文和負號

plt.rcParams[‘font.sans-serif’]=[‘Microsoft Yahei’]
plt.rcParams[‘axes.unicode_minus’]=False

gdp = pd.read_excel(r’北京市各區縣歷年GDP數據及各區縣對全市的貢獻率、拉動率.xls’,sheet_name=‘GDP’,index_col=0)
gdp.head(3)

部分問題解決方案


路漫漫其修遠兮,吾將上下而求索

參考資料


  1. 從零開始學Python數據分析與挖掘/劉順祥著.—北京:清華大學出版社,2018ISBN 978-7-302-50987-5 ↩︎

  2. 強烈推薦一款Python可視化神器!強烈必備 ↩︎

  3. 可視化神器Plotly_Express詳解 ↩︎

  4. pyecharts官方文檔 ↩︎

  5. pyecharts-gallery ↩︎

  6. 重磅!你們一直催的 PyEcharts教程來啦 ↩︎

  7. pyecharts可視化結果 ↩︎

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章