我用Python的Seaborn庫繪製17個超好看圖表

點擊上方「 Python爬蟲與數據挖掘 」,進行關注

回覆「書籍」便可獲贈Python從入門到進階共10本電子書python

git

github

web

微信

風朝露夜陰晴裏,萬戶千門開閉時。


Seaborn簡介

定義

Seaborn是一個基於matplotlib且數據結構與pandas統一的統計圖製做庫。Seaborn框架旨在以數據可視化爲中心來挖掘與理解數據。數據結構

優勢

  1. 代碼較少app

  2. 圖形美觀框架

  3. 功能齊全less

  4. 主流模塊安裝編輯器

pip命令安裝

pip install matplotlib
pip install seaborn

從github安裝

pip install git+https://github.com/mwaskom/seaborn.git

流程

導入繪圖模塊

mport matplotlib.pyplot as plt
import seaborn as sns

提供顯示條件

%matplotlib inline  #在Jupyter中正常顯示圖形

導入數據

#Seaborn內置數據集導入
dataset = sns.load_dataset('dataset')

#外置數據集導入(以csv格式爲例)
dataset = pd.read_csv('dataset.csv')

設置畫布

#設置一塊大小爲(12,6)的畫布
plt.figure(figsize=(12, 6))

輸出圖形

#總體圖形背景樣式,共5種:"white", "dark", "whitegrid", "darkgrid", "ticks"
sns.set_style('white')

#以條形圖爲例輸出圖形
sns.barplot(x=x,y=y,data=dataset,...)

'''
barplot()括號裏的是須要設置的具體參數,
涉及到數據、顏色、座標軸、以及具體圖形的一些控制變量,
基本的一些參數包括'x'、'y'、'data',分別表示x軸,y軸,
以及選擇的數據集。
'''

保存圖形

#將畫布保存爲png、jpg、svg等格式圖片
plt.savefig('jg.png')

實戰

#數據準備
df = pd.read_csv('./cook.csv') #讀取數據集(「菜J學Python」公衆號後臺回覆cook獲取)
df['難度'] = df['用料數'].apply(lambda x:'簡單' if x<5 else('通常' if x<15 else '較難')) #增長難度字段
df = df[['菜譜','用料','用料數','難度','菜系','評分','用戶']] #選擇須要的列
df.sample(5) #查看數據集的隨機5行數據


#導入相關包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns
%matplotlib inline
plt.rcParams['font.sans-serif'] = ['SimHei'] # 設置加載的字體名
plt.rcParams['axes.unicode_minus'] = False # 解決保存圖像是負號'-'顯示爲方塊的問題
sns.set_style('white') #設置圖形背景樣式爲white

直方圖

#語法
'''
seaborn.distplot(a, bins=None, hist=True, kde=True, rug=False, fit=None,
hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None, color=None,
vertical=False, norm_hist=False, axlabel=None, label=None, ax=None)
'''


#distplot()輸出直方圖,默認擬合出密度曲線
plt.figure(figsize=(10, 6)) #設置畫布大小
rate = df['評分']
sns.distplot(rate,color="salmon",bins=20) #參數color樣式爲salmon,bins參數設定數據片斷的數量


#kde參數設爲False,可去掉擬合的密度曲線
plt.figure(figsize=(10, 6))
sns.distplot(rate,kde=False,color="salmon",bins=20)


#設置rug參數,可添加觀測數值的邊際毛毯
fig,axes=plt.subplots(1,2,figsize=(10,6)) #爲方便對比,建立一個1行2列的畫布,figsize設置畫布大小

sns.distplot(rate,color="salmon",bins=10,ax=axes[0]) #axes[0]表示第一張圖(左圖)

sns.distplot(rate,color="green",bins=10,rug=True,ax=axes[1]) #axes[1]表示第一張圖(右圖)


#多個參數可經過字典傳遞
fig,axes=plt.subplots(1,2,figsize=(10,6))
sns.distplot(rate,color="salmon",bins=20,rug=True,ax=axes[0])

sns.distplot(rate,rug=True,
hist_kws={'color':'g','label':'直方圖'},
kde_kws={'color':'b','label':'密度曲線'},
bins=20,
ax=axes[1])


散點圖

常規散點圖:scatterplot

#語法
'''
seaborn.scatterplot(x=None, y=None, hue=None, style=None, size=None,
data=None, palette=None, hue_order=None, hue_norm=None, sizes=None,
size_order=None, size_norm=None, markers=True, style_order=None, x_bins=None,
y_bins=None, units=None, estimator=None, ci=95, n_boot=1000, alpha='auto',
x_jitter=None, y_jitter=None, legend='brief', ax=None, **kwargs)
'''


fig,axes=plt.subplots(1,2,figsize=(10,6))
#hue參數,對數據進行細分
sns.scatterplot(x="用料數", y="評分",hue="難度",data=df,ax=axes[0])

#style參數經過不一樣的顏色和標記顯示分組變量
sns.scatterplot(x="用料數", y="評分",hue="難度",style='難度',data=df,ax=axes[1])


分簇散點圖:stripplot

#語法
'''
seaborn.stripplot(x=None, y=None, hue=None, data=None, order=None,
hue_order=None, jitter=True, dodge=False, orient=None, color=None,
palette=None, size=5, edgecolor='gray', linewidth=0, ax=None, **kwargs)
'''


#設置jitter參數控制抖動的大小
plt.figure(figsize=(10, 6))
sns.stripplot(x="菜系", y="評分",hue="難度",jitter=1,data=df)


分類散點圖:swarmplot

#繪製分類散點圖(帶分佈屬性)
#語法
'''
seaborn.swarmplot(x=None, y=None, hue=None, data=None, order=None,
hue_order=None, dodge=False, orient=None, color=None, palette=None,
size=5, edgecolor='gray', linewidth=0, ax=None, **kwargs)
'''


plt.figure(figsize=(10, 6))
sns.swarmplot(x="菜系", y="評分",hue="難度",data=df)


條形圖

常規條形圖:barplot

#語法
'''
seaborn.barplot(x=None, y=None, hue=None, data=None, order=None,
hue_order=None,ci=95, n_boot=1000, units=None, orient=None, color=None,
palette=None, saturation=0.75, errcolor='.26', errwidth=None, capsize=None,
ax=None, estimator=<function mean>,**kwargs)
'''


#barplot()默認展現的是某種變量分佈的平均值(可經過修改estimator參數爲max、min、median等)
# from numpy import median
fig,axes=plt.subplots(1,2,figsize=(10,6))
sns.barplot(x='菜系',y='評分',color="r",data=df,ax=axes[0])

sns.barplot(x='菜系',y='評分',color="salmon",data=df,estimator=min,ax=axes[1])


fig,axes=plt.subplots(1,2,figsize=(10,6))
#設置hue參數,對x軸的數據進行細分
sns.barplot(x='菜系',y='評分',color="salmon",hue='難度',data=df,ax=axes[0])
#調換x和y的順序,可將縱向條形圖轉爲水平條形圖
sns.barplot(x='評分',y='菜系',color="salmon",hue='難度',data=df,ax=axes[1])


計數條形圖:countplot

#語法
'''
seaborn.countplot(x=None, y=None, hue=None, data=None, order=None,
hue_order=None, orient=None, color=None, palette=None, saturation=0.75, dodge=True, ax=None, **kwargs)
'''


fig,axes=plt.subplots(1,2,figsize=(10,6))
#選定某個字段,countplot()會自動統計該字段下各種別的數目
sns.countplot(x='菜系',color="salmon",data=df,ax=axes[0])
#一樣能夠加入hue參數
sns.countplot(x='菜系',color="salmon",hue='難度',data=df,ax=axes[1])


折線圖

#語法
'''
seaborn.lineplot(x=None, y=None, hue=None, size=None, style=None,
data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None,
size_norm=None, dashes=True, markers=None, style_order=None, units=None, estimator='mean',
ci=95, n_boot=1000, sort=True, err_style='band', err_kws=None, legend='brief', ax=None, **kwargs)
'''


fig,axes=plt.subplots(1,2,figsize=(10,6))
#默認折線圖有聚合
sns.lineplot(x="用料數", y="評分", hue="菜系",data=df,ax=axes[0])

#estimator參數設置爲None可取消聚合
sns.lineplot(x="用料數", y="評分", hue="菜系",estimator=None,data=df,ax=axes[1])


箱圖

箱線圖:boxplot

#語法
'''
seaborn.boxplot(x=None, y=None, hue=None, data=None, order=None,
hue_order=None, orient=None, color=None, palette=None, saturation=0.75,
width=0.8, dodge=True, fliersize=5, linewidth=None, whis=1.5, notch=False, ax=None, **kwargs)
'''

fig,axes=plt.subplots(1,2,figsize=(10,6))
sns.boxplot(x='菜系',y='評分',hue='難度',data=df,ax=axes[0])

#調節order和hue_order參數,能夠控制x軸展現的順序,linewidth調節線寬
sns.boxplot(x='菜系',y='評分',hue='難度',data=df,color="salmon",linewidth=1,
order=['清真菜','粵菜','東北菜','魯菜','浙菜','湖北菜','川菜'],
hue_order=['簡單','通常','較難'],ax=axes[1])


箱型圖:boxenplot

#語法
'''
seaborn.boxenplot(x=None, y=None, hue=None, data=None, order=None,
hue_order=None, orient=None, color=None, palette=None, saturation=0.75,
width=0.8, dodge=True, k_depth='proportion', linewidth=None, scale='exponential',
outlier_prop=None, ax=None, **kwargs)
'''


fig,axes=plt.subplots(1,2,figsize=(10,6))
sns.boxenplot(x='菜系',y='評分',hue='難度',data=df,color="salmon",ax=axes[0])

#palette參數可設置調色板
sns.boxenplot(x='菜系',y='評分',hue='難度',data=df, palette="Set2",ax=axes[1])


小提琴圖

#語法
'''
seaborn.violinplot(x=None, y=None, hue=None, data=None, order=None,
hue_order=None, bw='scott', cut=2, scale='area', scale_hue=True,
gridsize=100, width=0.8, inner='box', split=False, dodge=True, orient=None,
linewidth=None, color=None, palette=None, saturation=0.75, ax=None, **kwargs)
'''


fig,axes=plt.subplots(1,2,figsize=(10,6))
sns.violinplot(x='菜系',y='評分',data=df, color="salmon",linewidth=1,ax=axes[0])
#inner參數可在小提琴內部添加圖形,palette設置顏色漸變
sns.violinplot(x='菜系',y='評分',data=df,palette=sns.color_palette('Greens'),inner='stick',ax=axes[1])


迴歸圖

regplot

'''
seaborn.regplot(x, y, data=None, x_estimator=None, x_bins=None, x_ci='ci',
scatter=True, fit_reg=True, ci=95, n_boot=1000, units=None,
order=1, logistic=False, lowess=False, robust=False, logx=False,
x_partial=None, y_partial=None, truncate=False, dropna=True,
x_jitter=None, y_jitter=None, label=None, color=None, marker='o',
scatter_kws=None, line_kws=None, ax=None)
'''


fig,axes=plt.subplots(1,2,figsize=(10,6))
#marker參數可設置數據點的形狀
sns.regplot(x='用料數',y='評分',data=df,color='r',marker='+',ax=axes[0])
#ci參數設置爲None可去除直線附近陰影(置信區間)
sns.regplot(x='用料數',y='評分',data=df,ci=None,color='g',marker='*',ax=axes[1])


lmplot

#語法
'''
seaborn.lmplot(x, y, data, hue=None, col=None, row=None, palette=None,
col_wrap=None, height=5, aspect=1, markers='o', sharex=True,
sharey=True, hue_order=None, col_order=None, row_order=None,
legend=True, legend_out=True, x_estimator=None, x_bins=None,
x_ci='ci', scatter=True, fit_reg=True, ci=95, n_boot=1000,
units=None, order=1, logistic=False, lowess=False, robust=False,
logx=False, x_partial=None, y_partial=None, truncate=False,
x_jitter=None, y_jitter=None, scatter_kws=None, line_kws=None, size=None)
'''


#lmplot()能夠設置hue,進行多個類別的顯示,而regplot()是不支持的
sns.lmplot(x='用料數',y='評分',hue='難度',data=df,
palette=sns.color_palette('Reds'),ci=None,markers=['*','o','+'])


熱力圖

#語法
'''
seaborn.heatmap(data, vmin=None, vmax=None, cmap=None, center=None,
robust=False, annot=None, fmt='.2g', annot_kws=None,
linewidths=0, linecolor='white', cbar=True, cbar_kws=None,
cbar_ax=None, square=False, xticklabels='auto',
yticklabels='auto', mask=None, ax=None, **kwargs)
'''


fig,axes=plt.subplots(1,2,figsize=(10,6))
h=pd.pivot_table(df,index=['菜系'],columns=['難度'],values=['評分'],aggfunc=np.mean)
sns.heatmap(h,ax=axes[0])

#annot參數設置爲True可顯示數字,cmap參數可設置熱力圖調色板
cmap = sns.diverging_palette(200,20,sep=20,as_cmap=True)
sns.heatmap(h,annot=True,cmap=cmap,ax=axes[1])
#保存圖形
plt.savefig('jg.png')

歡迎關注菜J學Python,專一用Python爬蟲、數據分析和可視化。咱們堅持認真寫Python基礎,有趣寫Python實戰。

------------------- End -------------------

往期精彩文章推薦:

歡迎你們點贊,留言,轉發,轉載,感謝你們的相伴與支持

想加入Python學習羣請在後臺回覆【入羣

萬水千山老是情,點個【在看】行不行

/今日留言主題/

隨便說一兩句吧~~

本文分享自微信公衆號 - Python爬蟲與數據挖掘(crawler_python)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索