seaborn學(xué)習(xí)總結(jié)

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
np.random.seed(30)
x=np.random.normal(0,1,1000)
y=np.random.normal(0,1,1000)

六角圖

sns.jointplot(x=x,y=y,kind='hex')
<seaborn.axisgrid.JointGrid at 0x1a1fb97978>

六角圖可以顯示出點(diǎn)集中的區(qū)域

plt.rcParams['figure.figsize']=(6,6)
import warnings
warnings.simplefilter('error', 'UserWarning')

密度分布圖

sns.set()
ax=plt.subplot(111)
sns.kdeplot(x,y,ax=ax,color='m')
# sns.jointplot(x,y,kind='kde')
sns.rugplot(x, ax=ax,color='g')
sns.rugplot(y, vertical=True,ax=ax)
# plt.grid(True)
<matplotlib.axes._subplots.AxesSubplot at 0x1a219b3cf8>
iris=sns.load_dataset('iris')

PairPlot繪制出多個(gè)變量兩兩組合的繪圖

help(sns.pairplot)
Help on function pairplot in module seaborn.axisgrid:

pairplot(data, hue=None, hue_order=None, palette=None, vars=None, x_vars=None, y_vars=None, kind='scatter', diag_kind='auto', markers=None, height=2.5, aspect=1, dropna=True, plot_kws=None, diag_kws=None, grid_kws=None, size=None)
    Plot pairwise relationships in a dataset.
    
    By default, this function will create a grid of Axes such that each
    variable in ``data`` will by shared in the y-axis across a single row and
    in the x-axis across a single column. The diagonal Axes are treated
    differently, drawing a plot to show the univariate distribution of the data
    for the variable in that column.
    
    It is also possible to show a subset of variables or plot different
    variables on the rows and columns.
    
    This is a high-level interface for :class:`PairGrid` that is intended to
    make it easy to draw a few common styles. You should use :class:`PairGrid`
    directly if you need more flexibility.
    
    Parameters
    ----------
    data : DataFrame
        Tidy (long-form) dataframe where each column is a variable and
        each row is an observation.
    hue : string (variable name), optional
        Variable in ``data`` to map plot aspects to different colors.
    hue_order : list of strings
        Order for the levels of the hue variable in the palette
    palette : dict or seaborn color palette
        Set of colors for mapping the ``hue`` variable. If a dict, keys
        should be values  in the ``hue`` variable.
    vars : list of variable names, optional
        Variables within ``data`` to use, otherwise use every column with
        a numeric datatype.
    {x, y}_vars : lists of variable names, optional
        Variables within ``data`` to use separately for the rows and
        columns of the figure; i.e. to make a non-square plot.
    kind : {'scatter', 'reg'}, optional
        Kind of plot for the non-identity relationships.
    diag_kind : {'auto', 'hist', 'kde'}, optional
        Kind of plot for the diagonal subplots. The default depends on whether
        ``"hue"`` is used or not.
    markers : single matplotlib marker code or list, optional
        Either the marker to use for all datapoints or a list of markers with
        a length the same as the number of levels in the hue variable so that
        differently colored points will also have different scatterplot
        markers.
    height : scalar, optional
        Height (in inches) of each facet.
    aspect : scalar, optional
        Aspect * height gives the width (in inches) of each facet.
    dropna : boolean, optional
        Drop missing values from the data before plotting.
    {plot, diag, grid}_kws : dicts, optional
        Dictionaries of keyword arguments.
    
    Returns
    -------
    grid : PairGrid
        Returns the underlying ``PairGrid`` instance for further tweaking.
    
    See Also
    --------
    PairGrid : Subplot grid for more flexible plotting of pairwise
               relationships.
    
    Examples
    --------
    
    Draw scatterplots for joint relationships and histograms for univariate
    distributions:
    
    .. plot::
        :context: close-figs
    
        >>> import seaborn as sns; sns.set(style="ticks", color_codes=True)
        >>> iris = sns.load_dataset("iris")
        >>> g = sns.pairplot(iris)
    
    Show different levels of a categorical variable by the color of plot
    elements:
    
    .. plot::
        :context: close-figs
    
        >>> g = sns.pairplot(iris, hue="species")
    
    Use a different color palette:
    
    .. plot::
        :context: close-figs
    
        >>> g = sns.pairplot(iris, hue="species", palette="husl")
    
    Use different markers for each level of the hue variable:
    
    .. plot::
        :context: close-figs
    
        >>> g = sns.pairplot(iris, hue="species", markers=["o", "s", "D"])
    
    Plot a subset of variables:
    
    .. plot::
        :context: close-figs
    
        >>> g = sns.pairplot(iris, vars=["sepal_width", "sepal_length"])
    
    Draw larger plots:
    
    .. plot::
        :context: close-figs
    
        >>> g = sns.pairplot(iris, height=3,
        ...                  vars=["sepal_width", "sepal_length"])
    
    Plot different variables in the rows and columns:
    
    .. plot::
        :context: close-figs
    
        >>> g = sns.pairplot(iris,
        ...                  x_vars=["sepal_width", "sepal_length"],
        ...                  y_vars=["petal_width", "petal_length"])
    
    Use kernel density estimates for univariate plots:
    
    .. plot::
        :context: close-figs
    
        >>> g = sns.pairplot(iris, diag_kind="kde")
    
    Fit linear regression models to the scatter plots:
    
    .. plot::
        :context: close-figs
    
        >>> g = sns.pairplot(iris, kind="reg")
    
    Pass keyword arguments down to the underlying functions (it may be easier
    to use :class:`PairGrid` directly):
    
    .. plot::
        :context: close-figs
    
        >>> g = sns.pairplot(iris, diag_kind="kde", markers="+",
        ...                  plot_kws=dict(s=50, edgecolor="b", linewidth=1),
        ...                  diag_kws=dict(shade=True))
sns.pairplot(iris,kind='reg',diag_kind='kde',markers='o')
<seaborn.axisgrid.PairGrid at 0x1a2145a4a8>

PairGrid的繪圖原理是先產(chǎn)生4\times4=16個(gè)數(shù)據(jù)組合报辱,然后再分別選擇對角線和非對角線上的映射形式聚请。

g=sns.PairGrid(iris)

g.map_diag(sns.kdeplot)
g.map_offdiag(sns.kdeplot,n_levels=20)
<seaborn.axisgrid.PairGrid at 0x1a22dd5d30>

探索變量間的關(guān)系

tips=sns.load_dataset('tips')
tips.head()

散點(diǎn)+線性回歸擬合線+95%置信區(qū)間

sns.lmplot(data=tips,x='size', y='tip')
<seaborn.axisgrid.FacetGrid at 0x1a28925b00>

看不清楚點(diǎn)的時(shí)候,因?yàn)閤方向上很多點(diǎn)都重合了

方法一:加個(gè)抖動(dòng)

sns.lmplot(data=tips,x='size', y='tip',x_jitter=0.08)
<seaborn.axisgrid.FacetGrid at 0x1a28b979b0>
anscombe=sns.load_dataset('anscombe')
anscombe.head()

我們可以通過設(shè)定order的參數(shù)來限定用來擬合的次數(shù)

sns.lmplot(data=anscombe.query("dataset == 'II'"), x='x', y='y',order=2)
<seaborn.axisgrid.FacetGrid at 0x1a28c7ed30>

如果有異常值议惰,需要傳入一個(gè)robust=True的參數(shù)來限定不將異常值點(diǎn)也納入到擬合內(nèi)

sns.lmplot(data=anscombe.query("dataset == 'III'"), x='x', y='y')
<seaborn.axisgrid.FacetGrid at 0x1a28c68240>
sns.lmplot(data=anscombe.query("dataset == 'III'"), x='x', y='y', robust=True,ci=None)
<seaborn.axisgrid.FacetGrid at 0x1a28d267f0>
sns.lmplot(data=tips,x='total_bill',y='if_smoker',logistic=True)
<seaborn.axisgrid.FacetGrid at 0x1a26c0b4a8>

我們可以設(shè)定一個(gè)logistic=True的參數(shù)來擬合二分類問題铲敛。

x=np.random.normal(0,1,1000)
y=np.random.normal(1,3,1000)
ax=plt.subplot(111)

ax2=ax.twinx()

sns.kdeplot(x,ax=ax)
sns.kdeplot(y,ax=ax2)
<matplotlib.axes._subplots.AxesSubplot at 0x1a25ddb6d8>
tips.head()

回歸散點(diǎn)圖

sns.lmplot(data=tips,x='total_bill', y='tip',hue='smoker')
<seaborn.axisgrid.FacetGrid at 0x1a25e60f28>

我們可以傳入hue參數(shù)對數(shù)據(jù)進(jìn)行分類別的展示

sns.lmplot(data=tips,x='total_bill', y='tip',hue='day')
<seaborn.axisgrid.FacetGrid at 0x1a2a3ec940>

結(jié)論:從上面大致可以看出星期天人們不太愿意給小費(fèi)

還可以傳入colrow參數(shù)進(jìn)行分子圖展示

height設(shè)置圖的高度膜眠,aspect設(shè)置圖的壓縮比

sns.lmplot(data=tips,x='total_bill', y='tip',hue='smoker', col='time', row='sex',height=10,aspect=0.7)
<seaborn.axisgrid.FacetGrid at 0x1a2f38e978>

swarmplot

swarmplot用于分類散點(diǎn)圖,避免點(diǎn)的重疊

sns.swarmplot(data=tip,x='day',y='tip')
<matplotlib.axes._subplots.AxesSubplot at 0x1a27dba208>

小提琴圖

箱圖+kde圖

sns.violinplot(data=tips,x='day',y='tip',hue='sex')
<matplotlib.axes._subplots.AxesSubplot at 0x1a275cee10>

非對稱小提琴圖

非對稱小提琴圖適用于兩種類別的hue同時(shí)畫在左右兩邊一起對比

sns.violinplot(data=tips,x='day',y='tip',split=True,hue='sex',inner='stick')
<matplotlib.axes._subplots.AxesSubplot at 0x1a2636fdd8>

灰度柱狀圖

類似于pandasvalue_counts()函數(shù)對某個(gè)列進(jìn)行分類統(tǒng)計(jì)后繪制的圖脚牍。

sns.countplot(tips.smoker)
plt.legend(('Yes', 'No'))
<matplotlib.legend.Legend at 0x1a26b898d0>
tips['smoker'].head()
0    No
1    No
2    No
3    No
4    No
Name: smoker, dtype: category
Categories (2, object): [Yes, No]
type(tips)
pandas.core.frame.DataFrame
tips['if_smoker']=tips['smoker'].map({'Yes':1, 'No':0})
tips.if_smoker.head()
0    0
1    0
2    0
3    0
4    0
Name: if_smoker, dtype: int64

我們可以自由選擇進(jìn)入PairGrid的變量

tips.head()
g=sns.PairGrid(tips,x_vars=['smoker','sex', 'day'],y_vars=['total_bill','tip'],height=5, aspect=0.7)
g.map(sns.violinplot, palette='bright')
<seaborn.axisgrid.PairGrid at 0x1a278fa4e0>

前面用到的是g.map_diagg.map_offdiag分別是設(shè)置對角線和非對角線的繪制圖類型向臀,適用于方陣的情況,如果是統(tǒng)一設(shè)置則用g.map即可

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末诸狭,一起剝皮案震驚了整個(gè)濱河市券膀,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌驯遇,老刑警劉巖芹彬,帶你破解...
    沈念sama閱讀 218,451評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異叉庐,居然都是意外死亡舒帮,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評論 3 394
  • 文/潘曉璐 我一進(jìn)店門陡叠,熙熙樓的掌柜王于貴愁眉苦臉地迎上來玩郊,“玉大人,你說我怎么就攤上這事枉阵∫牒欤” “怎么了?”我有些...
    開封第一講書人閱讀 164,782評論 0 354
  • 文/不壞的土叔 我叫張陵兴溜,是天一觀的道長侦厚。 經(jīng)常有香客問我,道長拙徽,這世上最難降的妖魔是什么刨沦? 我笑而不...
    開封第一講書人閱讀 58,709評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮斋攀,結(jié)果婚禮上已卷,老公的妹妹穿的比我還像新娘。我一直安慰自己淳蔼,他們只是感情好侧蘸,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評論 6 392
  • 文/花漫 我一把揭開白布裁眯。 她就那樣靜靜地躺著,像睡著了一般讳癌。 火紅的嫁衣襯著肌膚如雪穿稳。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,578評論 1 305
  • 那天晌坤,我揣著相機(jī)與錄音逢艘,去河邊找鬼。 笑死骤菠,一個(gè)胖子當(dāng)著我的面吹牛它改,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播商乎,決...
    沈念sama閱讀 40,320評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼央拖,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了鹉戚?” 一聲冷哼從身側(cè)響起鲜戒,我...
    開封第一講書人閱讀 39,241評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎抹凳,沒想到半個(gè)月后遏餐,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,686評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡赢底,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評論 3 336
  • 正文 我和宋清朗相戀三年失都,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片颖系。...
    茶點(diǎn)故事閱讀 39,992評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡嗅剖,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出嘁扼,到底是詐尸還是另有隱情,我是刑警寧澤黔攒,帶...
    沈念sama閱讀 35,715評論 5 346
  • 正文 年R本政府宣布趁啸,位于F島的核電站,受9級特大地震影響督惰,放射性物質(zhì)發(fā)生泄漏不傅。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評論 3 330
  • 文/蒙蒙 一赏胚、第九天 我趴在偏房一處隱蔽的房頂上張望访娶。 院中可真熱鬧,春花似錦觉阅、人聲如沸崖疤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽劫哼。三九已至叮趴,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間权烧,已是汗流浹背眯亦。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留般码,地道東北人妻率。 一個(gè)月前我還...
    沈念sama閱讀 48,173評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像板祝,于是被迫代替她去往敵國和親舌涨。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評論 2 355

推薦閱讀更多精彩內(nèi)容