美文网首页
可视化库Seaborn

可视化库Seaborn

作者: ForgetThatNight | 来源:发表于2018-07-09 22:13 被阅读27次
    %matplotlib inline
    import numpy as np
    import pandas as pd
    import seaborn as sns
    np.random.seed(22)
    
    
    x = np.linspace(0, 15, 31)
    data = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1)
    print (data)
    ax = sns.tsplot(data=data)
    

    输出 :

    [[ 0.6726167   1.42526277  1.72616519  2.32083315  1.54461515  1.40149227
       0.87580901  0.80441429 -0.07224181  0.29857697 -0.48424123  0.31981954
       0.99846686  1.42437645  1.31025412  1.40829701  2.22555828  2.22047545
       1.57821254  0.68658331  0.6881278   0.27267873 -0.14865056  0.20390982
       0.35513849  0.98212391  1.58695872  1.37983576  2.37803345  2.3879375
       1.79185478]
     [-0.43621914 -0.72288203 -0.21215386  0.64103881  0.42284559 -0.12482161
      -0.96193001 -1.09788291 -1.47241293 -1.89764937 -2.14464665 -1.49924358
      -1.41491481 -0.97105382  0.1104314   0.5558068  -0.11681849 -0.3038328
      -0.34620543 -1.10897653 -0.99378228 -1.50366581 -1.78787403 -1.12480698
      -1.05900142 -1.0789754  -0.64372858  0.11116598  0.07264423  0.61504814
      -0.4948404 ]
     [-1.15693699 -0.77244812  0.10712619  0.35502433  0.18285087 -0.69500184
      -0.47143782 -1.81628184 -1.87017035 -1.49539289 -1.48815891 -2.15350233
      -1.07741052 -1.0917767  -0.24589205 -0.29088809 -0.32379686 -0.16896109
      -0.48709739 -1.07620973 -1.50686489 -2.02695517 -1.58450287 -2.09462768
      -1.14549613 -0.90213673 -0.3536208  -0.636773    0.17690764  0.46320646
      -0.3141777 ]
     [ 1.25380463  1.24138729  1.36265852  2.12250743  2.03812837  0.9775839
       1.25258492  0.42041733  0.41556718 -0.29395437 -0.43533777  0.48780799
       0.64445138  1.36813161  1.0068781   1.96345548  2.07351304  1.51558318
       0.92671363  0.41493084  0.66663361  0.17240521  0.20836271 -0.28724893
       0.44840531  0.68982403  1.25599442  1.69034134  1.34628125  2.12844035
       1.32152215]
     [-0.84609652 -0.89816345 -0.49457141  0.54579892 -0.26359758 -0.06168502
      -0.84582269 -0.99970035 -1.49066269 -1.43749266 -1.72981359 -2.05344609
      -1.54883698 -0.41343364 -0.27623244  0.15767716  0.46806644 -0.08612928
      -0.15592946 -0.81101017 -1.47042735 -2.03572856 -1.54874078 -1.75006712
      -1.89485388 -1.2967029  -0.05614918 -0.54595656  0.07716932 -0.37122121
      -0.19485513]
     [-0.53838073 -0.70212995  0.54650868  0.19485874  0.64734142 -0.25855414
      -0.5139151  -1.30725201 -1.81140672 -1.69939543 -1.19462958 -1.43073257
      -1.17288844 -0.83052925 -0.53301551  0.25857166  0.2395146   0.42424807
      -0.41349669 -1.04744752 -0.77941367 -1.31466412 -2.17077125 -1.79316715
      -1.68731229 -0.55432485 -0.56025323 -0.07883656  0.41328362  0.53601282
       0.13839468]
     [ 0.23229141  1.08228128  1.05600827  1.48742917  0.91770588  1.27248518
       0.80114066 -0.06003443 -0.70538254 -1.14511358 -0.59191008 -0.36992571
      -0.40628147  0.6107723   1.46427013  1.57202347  1.40603705  1.41391492
       1.01592868  0.19941683 -0.32228602 -0.42298825 -1.07494005 -0.85824756
      -0.62460032  0.75777946  1.05374853  1.08352002  0.99758181  0.76573615
       1.15801937]
     [ 0.03610165  1.02871206  0.96814603  0.7247723   1.14117985  0.2259254
       0.24353815  0.06743878 -0.72757369 -0.91510488 -0.44771336 -0.38857891
      -0.12696506 -0.11729812  0.99414654  0.8724561   1.44012495  1.00738892
       0.44502326  0.14066926 -0.81797799 -0.90072781 -0.46746009 -0.74213525
      -0.40410056 -0.23328721  0.62472249  0.58969376  1.5430677   0.79848609
       0.82322971]
     [ 1.272267    1.67428346  2.10571679  2.08500924  1.52768777  1.76673356
       1.5941398   0.31618267  0.56094535 -0.05904032  0.06489984  0.13607848
       0.79207021  1.17543317  1.59665543  1.89809518  2.21612089  2.04581354
       1.2798722   0.53176206  0.39540754 -0.14805861  0.0922169   0.5504571
       0.06085842  0.50808191  1.00334308  1.68968381  1.56194559  1.51686319
       1.79781106]
     [ 2.75843589  3.02276048  3.64803647  3.2642171   3.67946998  3.74785894
       3.17628364  2.70551084  1.66156679  2.19246399  1.62189055  1.60772731
       1.97773633  2.89555072  3.39132847  3.1445841   3.75955263  3.05460622
       2.76118641  2.38280821  2.22139674  2.04374881  1.87766694  1.96670548
       2.05080123  2.57914958  3.18484661  3.32652216  4.02001749  3.91133834
       3.13133477]]
    
    gammas = sns.load_dataset("gammas")
    gammas.head(30)
    
    ax = sns.tsplot(time="timepoint", value="BOLD signal",
                     unit="subject", condition="ROI",
                     data=gammas)
    
    ax = sns.tsplot(data=data)
    
    ax = sns.tsplot(data=data, err_style="ci_bars", color="g")
    #{ci_band, ci_bars, boot_traces, boot_kde, unit_traces, unit_points}
    
    ax = sns.tsplot(data=data, err_style="ci_bars", interpolate=False)
    
    ax = sns.tsplot(data=data, estimator=np.median)
    
    ax = sns.tsplot(data=data, err_style="boot_traces", n_boot=500)
    
    ax = sns.tsplot(data=data, err_style="unit_traces")
    
    import seaborn as sns
    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    %matplotlib inline
    
    def sinplot(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)
    
    sinplot()
    
    sns.set()
    sinplot()
    

    5种主题风格

    • darkgrid
    • whitegrid
    • dark
    • white
    • ticks
    sns.set_style("whitegrid")
    data = np.random.normal(size=(20, 6)) + np.arange(6) / 2
    sns.boxplot(data=data)
    
    sns.set_style("dark")
    sinplot()
    
    sns.set_style("white")
    sinplot()
    
    sns.set_style("ticks")
    sinplot()
    
    sinplot()
    sns.despine()
    
    #f, ax = plt.subplots()
    sns.violinplot(data)
    sns.despine(offset=10)
    
    sns.set_style("whitegrid")
    sns.boxplot(data=data, palette="deep")
    sns.despine(left=True)
    
    with sns.axes_style("darkgrid"):
        plt.subplot(211)
        sinplot()
    plt.subplot(212)
    sinplot(-1)
    
    sns.set()
    
    sns.set_context("paper")
    plt.figure(figsize=(8, 6))
    sinplot()
    
    sns.set_context("talk")
    plt.figure(figsize=(8, 6))
    sinplot()
    
    sns.set_context("poster")
    plt.figure(figsize=(8, 6))
    sinplot()
    
    sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
    sinplot()
    
    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    %matplotlib inline
    sns.set(rc={"figure.figsize": (6, 6)})
    

    调色板

    • 颜色很重要
    • color_palette()能传入任何Matplotlib所支持的颜色
    • color_palette()不写参数则默认颜色
    • set_palette()设置所有图的颜色

    分类色板

    current_palette = sns.color_palette()
    sns.palplot(current_palette)
    

    6个默认的颜色循环主题: deep, muted, pastel, bright, dark, colorblind

    圆形画板

    当你有六个以上的分类要区分时,最简单的方法就是在一个圆形的颜色空间中画出均匀间隔的颜色(这样的色调会保持亮度和饱和度不变)。这是大多数的当他们需要使用比当前默认颜色循环中设置的颜色更多时的默认方案。

    最常用的方法是使用hls的颜色空间,这是RGB值的一个简单转换。

    sns.palplot(sns.color_palette("hls", 8))
    
    data = np.random.normal(size=(20, 8)) + np.arange(8) / 2
    sns.boxplot(data=data,palette=sns.color_palette("hls", 8))
    

    hls_palette()函数来控制颜色的亮度和饱和

    • l-亮度 lightness
    • s-饱和 saturation
    sns.palplot(sns.hls_palette(8, l=.7, s=.9))
    
    sns.palplot(sns.color_palette("Paired",8))
    

    使用xkcd颜色来命名颜色

    xkcd包含了一套众包努力的针对随机RGB色的命名。产生了954个可以随时通过xdcd_rgb字典中调用的命名颜色。

    plt.plot([0, 1], [0, 1], sns.xkcd_rgb["pale red"], lw=3)
    plt.plot([0, 1], [0, 2], sns.xkcd_rgb["medium green"], lw=3)
    plt.plot([0, 1], [0, 3], sns.xkcd_rgb["denim blue"], lw=3)
    
    colors = ["windows blue", "amber", "greyish", "faded green", "dusty purple"]
    sns.palplot(sns.xkcd_palette(colors))
    

    连续色板

    色彩随数据变换,比如数据越来越重要则颜色越来越深

    sns.palplot(sns.color_palette("Blues"))
    

    如果想要翻转渐变,可以在面板名称中添加一个_r后缀

    sns.palplot(sns.color_palette("BuGn_r"))
    

    cubehelix_palette()调色板

    色调线性变换

    sns.palplot(sns.color_palette("cubehelix", 8))
    
    sns.palplot(sns.cubehelix_palette(8, start=.5, rot=-.75))
    
    sns.palplot(sns.cubehelix_palette(8, start=.75, rot=-.150))
    

    light_palette() 和dark_palette()调用定制连续调色板

    sns.palplot(sns.light_palette("green"))
    
    sns.palplot(sns.dark_palette("purple"))
    
    sns.palplot(sns.light_palette("navy", reverse=True))
    
    x, y = np.random.multivariate_normal([0, 0], [[1, -.5], [-.5, 1]], size=300).T
    pal = sns.dark_palette("green", as_cmap=True)
    sns.kdeplot(x, y, cmap=pal);
    
    
    sns.palplot(sns.light_palette((210, 90, 60), input="husl"))
    
    %matplotlib inline
    import numpy as np
    import pandas as pd
    from scipy import stats, integrate
    import matplotlib.pyplot as plt
    
    import seaborn as sns
    sns.set(color_codes=True)
    np.random.seed(sum(map(ord, "distributions")))
    
    x = np.random.normal(size=100)
    sns.distplot(x,kde=False)
    
    sns.distplot(x, bins=20, kde=False)
    

    数据分布情况

    x = np.random.gamma(6, size=200)
    sns.distplot(x, kde=False, fit=stats.gamma)
    

    根据均值和协方差生成数据

    mean, cov = [0, 1], [(1, .5), (.5, 1)]
    data = np.random.multivariate_normal(mean, cov, 200)
    df = pd.DataFrame(data, columns=["x", "y"])
    df
    

    观测两个变量之间的分布关系最好用散点图

    sns.jointplot(x="x", y="y", data=df);
    
    x, y = np.random.multivariate_normal(mean, cov, 1000).T
    with sns.axes_style("white"):
        sns.jointplot(x=x, y=y, kind="hex", color="k")
    
    iris = sns.load_dataset("iris")
    sns.pairplot(iris)
    
    %matplotlib inline
    import numpy as np
    import pandas as pd
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    
    import seaborn as sns
    sns.set(color_codes=True)
    
    np.random.seed(sum(map(ord, "regression")))
    
    tips = sns.load_dataset("tips")
    
    tips.head()
    

    regplot()和lmplot()都可以绘制回归关系,推荐regplot()

    sns.regplot(x="total_bill", y="tip", data=tips)
    
    sns.lmplot(x="total_bill", y="tip", data=tips);
    
    sns.regplot(data=tips,x="size",y="tip")
    
    sns.regplot(x="size", y="tip", data=tips, x_jitter=.05)
    
    anscombe = sns.load_dataset("anscombe")
    sns.regplot(x="x", y="y", data=anscombe.query("dataset == 'I'"),
               ci=None, scatter_kws={"s": 100})
    
    sns.lmplot(x="x", y="y", data=anscombe.query("dataset == 'II'"),
               ci=None, scatter_kws={"s": 80})
    
    sns.lmplot(x="x", y="y", data=anscombe.query("dataset == 'II'"),
               order=2, ci=None, scatter_kws={"s": 80});
    
    sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips);
    
    sns.lmplot(x="total_bill", y="tip", hue="smoker", data=tips,
               markers=["o", "x"], palette="Set1");
    
    sns.lmplot(x="total_bill", y="tip", hue="smoker", col="time", data=tips);
    
    sns.lmplot(x="total_bill", y="tip", hue="smoker",
               col="time", row="sex", data=tips);
    
    f, ax = plt.subplots(figsize=(5, 5))
    sns.regplot(x="total_bill", y="tip", data=tips, ax=ax);
    

    col_wrap:“Wrap” the column variable at this width, so that the column facets span multiple rows

    size :Height (in inches) of each facet

    sns.lmplot(x="total_bill", y="tip", col="day", data=tips,
               col_wrap=2, size=4);
    
    sns.lmplot(x="total_bill", y="tip", col="day", data=tips,
               aspect=.8);
    
    %matplotlib inline
    import numpy as np
    import pandas as pd
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import seaborn as sns
    sns.set(style="whitegrid", color_codes=True)
    
    np.random.seed(sum(map(ord, "categorical")))
    titanic = sns.load_dataset("titanic")
    tips = sns.load_dataset("tips")
    iris = sns.load_dataset("iris")
    
    sns.stripplot(x="day", y="total_bill", data=tips);
    

    重叠是很常见的现象,但是重叠影响我观察数据的量了

    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", hue="sex",data=tips)
    
    sns.swarmplot(x="total_bill", y="day", hue="time", data=tips);
    

    盒图

    • IQR即统计学概念四分位距,第一/四分位与第三/四分位之间的距离
    • N = 1.5IQR 如果一个值>Q3+N或 < Q1-N,则为离群点
    sns.boxplot(x="day", y="total_bill", hue="time", data=tips);
    
    sns.violinplot(x="total_bill", y="day", hue="time", data=tips);
    
    sns.violinplot(x="day", y="total_bill", hue="sex", data=tips, split=True);
    
    sns.violinplot(x="day", y="total_bill", data=tips, inner=None)
    sns.swarmplot(x="day", y="total_bill", data=tips, color="w", alpha=.5)
    

    显示值的集中趋势可以用条形图

    sns.barplot(x="sex", y="survived", hue="class", data=titanic);
    

    点图可以更好的描述变化差异

    sns.pointplot(x="sex", y="survived", hue="class", data=titanic);
    
    sns.pointplot(x="class", y="survived", hue="sex", data=titanic,
                  palette={"male": "g", "female": "m"},
                  markers=["^", "o"], linestyles=["-", "--"]);
    

    宽形数据

    sns.boxplot(data=iris,orient="h");
    

    多层面板分类图

    sns.factorplot(x="day", y="total_bill", hue="smoker", data=tips)
    
    sns.factorplot(x="day", y="total_bill", hue="smoker", data=tips, kind="bar")
    
    sns.factorplot(x="day", y="total_bill", hue="smoker",
                   col="time", data=tips, kind="swarm")
    
    sns.factorplot(x="time", y="total_bill", hue="smoker",
                   col="day", data=tips, kind="box", size=4, aspect=.5)
    

    seaborn.factorplot(x=None, y=None, hue=None, data=None, row=None, col=None, col_wrap=None, estimator=, ci=95, n_boot=1000, units=None, order=None, hue_order=None, row_order=None, col_order=None, kind='point', size=4, aspect=1, orient=None, color=None, palette=None, legend=True, legend_out=True, sharex=True, sharey=True, margin_titles=False, facet_kws=None, **kwargs)

    Parameters:

    • x,y,hue 数据集变量 变量名
    • date 数据集 数据集名
    • row,col 更多分类变量进行平铺显示 变量名
    • col_wrap 每行的最高平铺数 整数
    • estimator 在每个分类中进行矢量到标量的映射 矢量
    • ci 置信区间 浮点数或None
    • n_boot 计算置信区间时使用的引导迭代次数 整数
    • units 采样单元的标识符,用于执行多级引导和重复测量设计 数据变量或向量数据
    • order, hue_order 对应排序列表 字符串列表
    • row_order, col_order 对应排序列表 字符串列表
    • kind : 可选:point 默认, bar 柱形图, count 频次, box 箱体, violin 提琴, strip 散点,swarm 分散点 size 每个面的高度(英寸) 标量 aspect 纵横比 标量 orient 方向 "v"/"h" color 颜色 matplotlib颜色 palette 调色板 seaborn颜色色板或字典 legend hue的信息面板 True/False legend_out 是否扩展图形,并将信息框绘制在中心右边 True/False share{x,y} 共享轴线 True/False
    %matplotlib inline
    import numpy as np
    import pandas as pd
    import seaborn as sns
    from scipy import stats
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    
    sns.set(style="ticks")
    np.random.seed(sum(map(ord, "axis_grids")))
    
    
    tips = sns.load_dataset("tips")
    tips.head()
    
    g = sns.FacetGrid(tips, col="time")
    
    g = sns.FacetGrid(tips, col="time")
    g.map(plt.hist, "tip");
    
    g = sns.FacetGrid(tips, col="sex", hue="smoker")
    g.map(plt.scatter, "total_bill", "tip", alpha=.7)
    g.add_legend();
    
    g = sns.FacetGrid(tips, row="smoker", col="time", margin_titles=True)
    g.map(sns.regplot, "size", "total_bill", color=".1", fit_reg=False, x_jitter=.1);
    
    g = sns.FacetGrid(tips, col="day", size=4, aspect=.5)
    g.map(sns.barplot, "sex", "total_bill");
    
    from pandas import Categorical
    ordered_days = tips.day.value_counts().index
    print (ordered_days)
    ordered_days = Categorical(['Thur', 'Fri', 'Sat', 'Sun'])
    g = sns.FacetGrid(tips, row="day", row_order=ordered_days,
                      size=1.7, aspect=4,)
    g.map(sns.boxplot, "total_bill");
    
    pal = dict(Lunch="seagreen", Dinner="gray")
    g = sns.FacetGrid(tips, hue="time", palette=pal, size=5)
    g.map(plt.scatter, "total_bill", "tip", s=50, alpha=.7, linewidth=.5, edgecolor="white")
    g.add_legend();
    
    g = sns.FacetGrid(tips, hue="sex", palette="Set1", size=5, hue_kws={"marker": ["^", "v"]})
    g.map(plt.scatter, "total_bill", "tip", s=100, linewidth=.5, edgecolor="white")
    g.add_legend();
    
    with sns.axes_style("white"):
        g = sns.FacetGrid(tips, row="sex", col="smoker", margin_titles=True, size=2.5)
    g.map(plt.scatter, "total_bill", "tip", color="#334488", edgecolor="white", lw=.5);
    g.set_axis_labels("Total bill (US Dollars)", "Tip");
    g.set(xticks=[10, 30, 50], yticks=[2, 6, 10]);
    g.fig.subplots_adjust(wspace=.02, hspace=.02);
    #g.fig.subplots_adjust(left  = 0.125,right = 0.5,bottom = 0.1,top = 0.9, wspace=.02, hspace=.02)
    
    iris = sns.load_dataset("iris")
    g = sns.PairGrid(iris)
    g.map(plt.scatter);
    
    g = sns.PairGrid(iris)
    g.map_diag(plt.hist)
    g.map_offdiag(plt.scatter);
    
    g = sns.PairGrid(iris, hue="species")
    g.map_diag(plt.hist)
    g.map_offdiag(plt.scatter)
    g.add_legend();
    
    g = sns.PairGrid(iris, vars=["sepal_length", "sepal_width"], hue="species")
    g.map(plt.scatter);
    
    g = sns.PairGrid(tips, hue="size", palette="GnBu_d")
    g.map(plt.scatter, s=50, edgecolor="white")
    g.add_legend();
    
    %matplotlib inline
    import matplotlib.pyplot as plt
    import numpy as np; 
    np.random.seed(0)
    import seaborn as sns;
    sns.set()
    
    
    uniform_data = np.random.rand(3, 3)
    print (uniform_data)
    heatmap = sns.heatmap(uniform_data)
    

    输出 :
    [[ 0.0187898 0.6176355 0.61209572]
    [ 0.616934 0.94374808 0.6818203 ]
    [ 0.3595079 0.43703195 0.6976312 ]]


    ax = sns.heatmap(uniform_data, vmin=0.2, vmax=0.5)
    
    normal_data = np.random.randn(3, 3)
    print (normal_data)
    ax = sns.heatmap(normal_data, center=0)
    

    输出 :
    [[ 0.3113635 -0.77602047 -0.30736481]
    [-0.36652394 1.11971196 -0.45792242]
    [ 0.4253934 -0.02797118 1.47598983]]


    flights = sns.load_dataset("flights")
    flights.head()
    
    flights = flights.pivot("month", "year", "passengers")
    print (flights)
    ax = sns.heatmap(flights)
    
    
    输出
    year       1949  1950  1951  1952  1953  1954  1955  1956  1957  1958  1959  \
    month                                                                         
    January     112   115   145   171   196   204   242   284   315   340   360   
    February    118   126   150   180   196   188   233   277   301   318   342   
    March       132   141   178   193   236   235   267   317   356   362   406   
    April       129   135   163   181   235   227   269   313   348   348   396   
    May         121   125   172   183   229   234   270   318   355   363   420   
    June        135   149   178   218   243   264   315   374   422   435   472   
    July        148   170   199   230   264   302   364   413   465   491   548   
    August      148   170   199   242   272   293   347   405   467   505   559   
    September   136   158   184   209   237   259   312   355   404   404   463   
    October     119   133   162   191   211   229   274   306   347   359   407   
    November    104   114   146   172   180   203   237   271   305   310   362   
    December    118   140   166   194   201   229   278   306   336   337   405   
    
    year       1960  
    month            
    January     417  
    February    391  
    March       419  
    April       461  
    May         472  
    June        535  
    July        622  
    August      606  
    September   508  
    October     461  
    November    390  
    December    432  
    
    ax = sns.heatmap(flights, annot=True,fmt="d")
    
    ax = sns.heatmap(flights, linewidths=.5)
    
    ax = sns.heatmap(flights, cmap="YlGnBu")
    
    ax = sns.heatmap(flights, cbar=False)
    

    相关文章

      网友评论

          本文标题:可视化库Seaborn

          本文链接:https://www.haomeiwen.com/subject/wxyouftx.html