Seaborn是基于matplotlib產(chǎn)生的一個模塊,專攻于統(tǒng)計(jì)可視化鹃操,可以和pandas進(jìn)行無縫鏈接仓坞,使初學(xué)者更容易上手。相對于matplotlib购岗,Seaborn語法更簡潔汰聋,兩者關(guān)系類似于numpy和pandas之間的關(guān)系。
2.1安裝:
1)linux系統(tǒng)
sudo pip install seaborn
2)window系統(tǒng)
pip install seaborn
2.2快速入門
import? as sns
sns.set(style="ticks")
from matplotlib import pyplot
# 加載數(shù)據(jù)集
tips = sns.load_dataset("tips")
# 繪圖
sns.boxplot(x="day", y="total_bill", hue="sex", data=tips, palette="PRGn")
sns.despine(offset=10, trim=True)
#圖片展示與保存
pyplot.savefig("GroupedBoxplots.png")
pyplot.show()
2.3seaborn常用方法
1喊积、單變量分析繪圖
1)分布的集中趨勢烹困,反映數(shù)據(jù)向其中心值靠攏或聚集的程度
x = np.random.normal(size=100)
sns.distplot(x, kde=True)# kde=False關(guān)閉核密度分布, rug表示在x軸上每個觀測上生成的小細(xì)條(邊際毛毯)
2、觀測兩個變量之間的分布關(guān)系最好用散點(diǎn)圖
1)直接擬合概率密度函數(shù)
sns.jointplot(x="x", y="y", data=df, kind="kde")
2)能夠更加直觀反映點(diǎn)的分布情況
hex圖 (數(shù)據(jù)量大的時(shí)候)?
最好黑白相間
數(shù)據(jù)量大時(shí)候乾吻,用hex圖髓梅,分辨出哪塊更多(顏色深淺)
mean, cov = [0, 1], [(1, .5), (.5, 1)]
data = np.random.multivariate_normal(mean, cov, 200)
df = pd.DataFrame(data, columns=["x", "y"])
x, y = np.random.multivariate_normal(mean, cov, 1000).T
with sns.axes_style("ticks"):
? ? sns.jointplot(x=x, y=y, kind="hex")?
3、多變量兩兩顯示
# 鵑尾花數(shù)據(jù)iris = sns.load_dataset("iris")
sns.pairplot(iris)
4绎签、Seaborn可視化各種繪圖操作
1枯饿、盒圖 box graph
import matplotlib.pyplot as plt
import numpy as np
盒圖關(guān)心中位數(shù)Q2、四分之一位Q1诡必、四分之三位Q3和離群點(diǎn)?
IQR = Q3 - Q1
如果Q1-1.5IQR或者Q3+1.5IQR就是離群點(diǎn)
tang_data = [np.random.normal(0, std, 100) for std in range(1,4)]
fig = plt.figure(figsize=(8,6))
plt.boxplot(tang_data, vert=True, notch=True)
plt.xticks([x+1 for x in range(len(tang_data))], ['x1', 'x2', 'x3'])
plt.xlabel('x')
plt.title('box plot')
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
2奢方、單特征繪制直方圖
1)distplot
x = np.random.normal(size=100)
sns.distplot(x, kde=False, bins=20)
2)countplot 計(jì)數(shù)圖
countplot 故名思意,計(jì)數(shù)圖爸舒,可將它認(rèn)為一種應(yīng)用到分類變量的直方圖蟋字,也可認(rèn)為它是用以比較類別間計(jì)數(shù)差,調(diào)用 count 函數(shù)的 barplot扭勉。
seaborn.countplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, orient=None, color=None, palette=None, saturation=0.75, ax=None, **kwargs)
x, y, hue: names of variables in data or vector data, optional
data: DataFrame, array, or list of arrays, optional
order, hue_order: lists of strings, optional #設(shè)置順序
orient: “v” | “h”, optional #設(shè)置水平或者垂直顯示
ax: matplotlib Axes, optional #設(shè)置子圖位置鹊奖,將在下節(jié)介紹繪圖基礎(chǔ)
3、分析兩個特征之間的關(guān)系涂炎,利用散點(diǎn)圖來表達(dá)
mean, cov = [0,1], [(1, .5), (.5,1)]
data = np.random.multivariate_normal(mean, cov, 200)
df = pd.DataFrame(data, columns=['X1', 'X2'])
sns.jointplot(x='X1', y='X2', data=df)
# kind = 'hex' ?# 六邊形
data = np.random.multivariate_normal(mean, cov, 2000).T
with sns.axes_style('white'):
????sns.jointplot(x=data[0], y=data[1], kind='hex', color='k')
4嫉入、看兩兩之間變量的關(guān)系
iris = sns.load_dataset('iris')
sns.pairplot(iris)
5焰盗、條形圖
sns.barplot(x='sex', y='survived', data=titanic, hue='class')
點(diǎn)圖,不看集中趨勢咒林,就看各自的變化
sns.pointplot(x='sex', y='survived', data=titanic, hue='class')
sns.pointplot(x='class', y='survived', data=titanic, hue='sex', palette={'male':'g','female':'m'}, markers=['^', 'o'], linestyles=['-','--'])
tips = sns.load_dataset('tips', data_home='.')
# jitter 震動
sns.stripplot(x='day', y='total_bill', data=tips, jitter=True)
sns.swarmplot(x='day', y='total_bill', data=tips)
sns.swarmplot(x='day', y='total_bill', data=tips, hue='sex')
sns.swarmplot(x='day', y='total_bill', data=tips, hue='time')
6熬拒、盒圖
sns.boxplot(x='day', y='total_bill', data=tips, hue='time')
7、小提琴圖
sns.violinplot(x='day', y='total_bill', data=tips, hue='sex', split=True)
sns.violinplot(x='day', y='total_bill', data=tips, inner=None, split=True)
sns.swarmplot(x='day', y='total_bill', data=tips, color='k', alpha=1.0)
8垫竞、熱力圖通過顏色一目了然的指定值的大小澎粟,以及變化的趨勢
uniform_data = np.random.rand(3,3)
sns.heatmap(uniform_data)
sns.heatmap(uniform_data, vmin=0.2, vmax=0.5)
normal_data = np.random.randn(3,3)
sns.heatmap(normal_data, center=0)
flights = sns.load_dataset('flights')
data = flights.pivot("month", "year", 'passengers')
sns.heatmap(data)
sns.heatmap(data, annot=True, fmt='d', linewidths=.5, cbar=False, cmap='YlGnBu')
9、設(shè)置畫圖的整體風(fēng)格
def sin_plot(flip=1):
????x = np.linspace(0, 14, 100)
????for i in range(1,7):
????????plt.plot(x, np.sin(x+i*.5)*(7-i)*flip)
sin_plot()
10欢瞪、有五種主題風(fēng)格活烙,darkgrid whitegrid dark white ticks
sns.set_style('darkgrid')
data = np.random.normal(size=(20,6)) + np.arange(6) / 2
sns.boxplot(data=data)
11、每一個子圖的風(fēng)格都可以不一樣遣鼓,with里面一個風(fēng)格啸盏,外面一個風(fēng)格
with sns.axes_style('whitegrid'):
????plt.subplot(211)
????sin_plot()
plt.subplot(212)
sin_plot(-1)
12、布局的風(fēng)格
sns.set_context("paper")
plt.figure(figsize=(8,6))
sin_plot()
sns.set_context("talk")
plt.figure(figsize=(8,6))
sin_plot()
sns.set_context("poster")
plt.figure(figsize=(8,6))
sin_plot()
sns.set_context("notebook", font_scale=3.5, rc={'lines.linewidth': 4.5})
plt.figure(figsize=(8,6))
sin_plot()