數據可視化實例(十二): 發散型條形圖 (matplotlib,pandas)


https://datawhalechina.github.io/pms50/#/chapter10/chapter10

如果您想根據單個指標查看項目的變化情況,並可視化此差異的順序和數量,那么散型條形圖 (Diverging Bars) 是一個很好的工具。

它有助於快速區分數據中組的性能,並且非常直觀,並且可以立即傳達這一點。 

導入所需要的庫

import numpy as np              # 導入numpy庫
import pandas as pd             # 導入pandas庫
import matplotlib as mpl        # 導入matplotlib庫
import matplotlib.pyplot as plt
import seaborn as sns           # 導入seaborn庫

設定圖像各種屬性

large = 22; med = 16; small = 12

params = {'axes.titlesize': large,    # 設置子圖上的標題字體
            'legend.fontsize': med,     # 設置圖例的字體
            'figure.figsize': (16, 10), # 設置圖像的畫布
           'axes.labelsize': med,      # 設置標簽的字體
            'xtick.labelsize': med,     # 設置x軸上的標尺的字體
            'ytick.labelsize': med,     # 設置整個畫布的標題字體
          'figure.titlesize': large}  
#plt.rcParams.update(params)           # 更新默認屬性
plt.style.use('seaborn-whitegrid')    # 設定整體風格
sns.set_style("white")                # 設定整體背景風格

程序代碼

# step1:導入數據

df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")
x = df.loc[:, 'mpg']                                              # 獲取mpg這一列數據
    # z-score 標准化(正太標准化):將數據按期屬性(按列進行)減去其均值,並處以其方差。得到的結果是,對於每個屬性/每列來說所有數據都聚集在0附近,方差為1。
df['mpg_z'] = (x - x.mean()) / x.std()
    # 列表推導式
    # 小於0__紅色,大於0__綠色
df['colors'] = ['red' if x <0 else 'green' for x in df['mpg_z']]  # 顏色標簽
df.sort_values('mpg_z', inplace = True)                           # 對'mpg_z這一列數據進行排序
df.reset_index(inplace = True)                                    # 對排序后的數據重置索引

 

# step2:繪制發散條形圖

    # 畫布
plt.figure(figsize = (14, 10),   # 畫布尺寸_(14, 10)
           dpi = 80)             # 分辨率__80
    # 發散條形圖
plt.hlines(df.index,             # 將y下標作為繪制直線的位置
          xmin = 0,              # 每一行的開頭
          xmax = df.mpg_z,       # 每一行的結尾
          colors = df.colors,    # 顏色,默認為'k'(黑色)
          alpha = 0.4,           # 色彩飽和度
          linewidth = 5)         # 線寬

 

# step3:裝飾圖像

    # x,y軸的標題
plt.gca().set(ylabel='$Model$', xlabel='$Mileage$')               # 獲取當前子圖,若沒有子圖則創建一個子圖,並設置橫, 縱坐標的名稱
    # y軸標簽
plt.yticks(df.index,             # 放置刻度的位置列表
          df.cars,               # 放置給定位置列表的標簽列表
          fontsize = 12)         # 字體尺寸
plt.title('Diverging Bars of Car Mileage', fontdict={'size':20})  # 設置圖像標題
    # 設置網格線
plt.grid(linestyle = '--',       # 網格線類型
         alpha = 0.5)            # 透明度

plt.show()                       # 顯示圖像 

 

 博文總結

matplotlib.pyplot.hlines()

matplotlib.pyplot.hlines(y, xmin, xmax, colors='k', linestyles='solid', label='', \*, data=None, \*\*kwargs)

Plot horizontal lines at each y from xmin to xmax.

Parameters:
y scalar or sequence of scalar

y-indexes where to plot the lines.

xmin, xmax scalar or 1D array-like

Respective beginning and end of each line. If scalars are provided, all lines will have same length.

colors array-like of colors, optional, default: 'k'
linestyles {'solid', 'dashed', 'dashdot', 'dotted'}, optional
label str, optional, default: ''
Returns:
lines LineCollection
Other Parameters:
**kwargs LineCollection properties.

 


免責聲明!

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



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