• seaborn


      Seaborn是基于matplotlib的Python数据可视化库。 它提供了一个高级界面,用于绘制引人入胜且内容丰富的统计图形。

    一  风格及调色盘

      风格

        1 sns.set()  模式格式

        2 sns.set_style()   手动选择样式,从 darkgrid, whitegrid, dark, white, ticks 手动选择一个

        3 sns.set_context()   手动选择,表现为图的大小,paper, notebook, talk, poster 选一个

        4 sns.despine() 我电脑上不生效,不知道为什么? 有限坐标轴的一些设定

        5 with sns.axes_style()  。使sns样式 只在一个cell中生效,否则,整个ipynb都是生效的。

       调色盘  

        1 sns.color_palette()  

          Return a list of colors defining a color palette.   [ deep, muted, bright, pastel, dark, colorblind ] 可以从这几个中选一个。

          其它风格样式

    # 其他颜色风格
    # 风格内容:Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, 
    # BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, 
    # Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples,
    # Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3, 
    # Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, 
    # autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, 
    # cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, 
    # gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv, 
    # hsv_r, icefire, icefire_r, inferno, inferno_r, jet, jet_r, magma, magma_r, mako, mako_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r, 
    # pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, rocket, rocket_r, seismic, seismic_r, spectral, spectral_r, spring, 
    # spring_r, summer, summer_r, terrain, terrain_r, viridis, viridis_r, vlag, vlag_r, winter, winter_r

          返回值实际上类似 [[0.056191110099001705, 0.1179883217868713, 0.11005894089498236], [0.203019021665379, 0.05622532361389985, 0.09410692718552574]]

        2 sns.set_palette()  

          Set the matplotlib color cycle using a seaborn palette. 设置调色盘。

          接收的参数就是 类似 [ [ 0.1,0.2,0.3] , [0.4,0.5,0.3 ] ]

        3 sns.husl_palette() / sns.hls_palette()

        4 sns.palplot() 

          Plot the values in a color palette as a horizontal array.

          就是讲类似 [ [ 0.1,0.2,0.3] , [0.4,0.5,0.3 ] ] ,转换成对应的具体的颜色。

        5 sns.cubehelix_palette()

          返回类似 [ [ 0.1,0.2,0.3] , [0.4,0.5,0.3 ] ]

        5 sns.light_palette( 'green' ) / sns.dark_palette( 'red' ) 

          某种程度上和 sns.palplot(sns.color_palette('Greens')) 一样。

        6 sns.diverging_palette()

          Make a diverging palette between two HUSL colors.

          这个方法和sns.heatmap() 方法的as_map参数 和 cmap有联系。应该有as_cmp都有关。

        补充: with sns.color_palette  和  sns.set_palette  都可以实现设置调色板。前者 我试验的结果是必须带with,而且只在一个cell中生效。

     二  分布数据可视化

      1 直方图与密度图

        sns.distplot

          接收单变量参数。 可以理解为将直方图,密度图,rug 融合在一起。

          换言之,单维度 可以用distplot

        sns.kdeplot

          接收单变量,双变量参数。当时单变量的时候,图示密度图;当是双变量的时候,图是热力图。n_levels 参数可以设置,函数介绍中没有,这个参数很关键。和shade参数配合使用 效果更佳。

          换言之,双维度,用 kdeplot

        sns.rugplot

          接收单变量。坐标轴上的小块。

        

    sns.kdeplot(data['a'],data['b'],shade=True,cbar=True,legend=True,n_levels=60,cmap='OrRd',shade_lowest=False)
    sns.kdeplot(data['c'],data['d'],shade=True,cbar=True,legend=True,n_levels=60,cmap='Blues',shade_lowest=False)
    sns.rugplot(data['a'],axis='x',color='r',alpha=0.3)
    sns.rugplot(data['b'],axis='y',color='r',alpha=0.3)
    plt.scatter(data['a'],data['b'],s=1,color='k')

     

       2 散点图

        1) 综合散点图

          part 1散点图 + 分布图 

            sns.jointplot( joint_kws=None, marginal_kws=None, annot_kws=None )

              Draw a plot of two variables with bivariate and univariate graphs。

              有很多参数。

          part2 可拆分绘制的散点图

            sns.JointGrid

              Grid for drawing a bivariate plot with marginal univariate plots 。 我个人觉的这个定义太TM准确了。

              j = sns.JointGrid

              j.plot_joint()

                Draw a bivariate plot of `x` and `y`.

              j.plot_marginals()

                Draw univariate plots for `x` and `y` separately

              j.ax_marg_x.hist / bar

                Draw the two marginal plots separately

         2)矩阵散点图

        sns.pairplot(hue=,palette=, var = [ ] )  

          Plot pairwise relationships in a dataset.

          有很多参数,重要的是hue参数,分类,和 palette 参数 ,颜色区分,var 可以提取想要的数据对比

        sns.PairGrid()

          Subplot grid for plotting pairwise relationships in a dataset.

          p=sns.PairGrid()

          p.map_diag

            Plot with a univariate function on each diagonal subplot

          p.map_lower

            Plot with a bivariate function on the lower diagonal subplots.

          p.map_offdiag

            Plot with a bivariate function on the off-diagonal subplots.

          p.map_upper

        具体细节不再赘述,官网连接 https://seaborn.pydata.org/

    三  分类数据可视化

       1 分类散点图

        sns.stripplot(jitter,dodge)

          Draw a scatterplot where one variable is categorical.

          dodge=True  会对 hue 进行第二次视觉上的分类。

        sns.swarmplot()

          Draw a categorical scatterplot with non-overlapping points.

        两者差不多,重要参数有 x,y,hue,order 。会根据x,y的定量还是定性数据,进行第一次分类,然后根据hue参数进行第二次分类。order,选择我们想要展示的数据。

       2 分布图

        sns.boxplot()

          Draw a box plot to show distributions with respect to categories.

        sns.violinplot( split= ,inner= ,scale='area')

          Draw a combination of boxplot and kernel density estimate.

          有这几个参数,可以多多注意下

        sns.lvplot()

          Draw a letter value plot to show distributions of large datasets.

          这个可能没什么乱用吧

      3 统计图

        sns.barplot()

          

           这种样式的。

    Show point estimates and confidence intervals as rectangular bars.
    
    A bar plot represents an estimate of central tendency for a numeric
    variable with the height of each rectangle and provides some indication of
    the uncertainty around that estimate using error bars

          典型实例如下,有个重要的方法  sns.set_color_code()

    data = sns.load_dataset('car_crashes')
    fig  = plt.figure(figsize=(16,14))
    ax1 = fig.add_subplot(1,1,1)
    data1 = data.sort_values(by='total',ascending=False)
    sns.set_color_codes('pastel')
    sns.barplot(x='total',y='abbrev',data=data1,color='r',label='total')
    sns.set_color_codes('muted')
    sns.barplot(x='speeding',y='abbrev',data=data1,color='r',label='speeding')
    
    plt.legend()
    sns.despine()

        sns.countplot()

          Show the counts of observations in each categorical bin using bars.

          只接受一个x,或者一个y

          

        sns.pointplot()

          Show point estimates and confidence intervals using scatter plot glyphs.

          

    四  线性关系数据可视化

      sns.lmplot

        Plot data and regression model fits across a FacetGrid.

        When thinking about how to assign variables to different facets, a general rule is that it makes sense to use ``hue`` for the most important comparison, followed by ``col`` and ``row``. However, always think about your particular dataset and the goals of the visualization you are creating.

        

        x参数,y参数 必须都是定量的。

        

    五  其它图表可视化

      sns.lineplot() 老版本是sns.tsplot()

        Draw a line plot with possibility of several semantic groupings.

        The relationship between x and y can be shown for different subsets of the data using the hue, size, and style parameters. These parameters control what visual semantics are used to identify the different subsets.

        hue,size,style 参数很重要。

        x,y 参数是离散的numeric。

        

      sns.heatmap()

        Plot rectangular data as a color-encoded matrix

        注意,第一个参数是 2D dataset that can be coerced into an ndarray。所以,会用到 dataframe.pivot 方法。

        

    sns.heatmap(flights,
                annot = True,      # 是否显示数值
                fmt = 'd',         # 格式化字符串
                linewidths = 0.2,  # 格子边线宽度
                #center = 100,      # 调色盘的色彩中心值,若没有指定,则以cmap为主
                #cmap = 'Reds',     # 设置调色盘
                cbar = True,       # 是否显示图例色带
                #cbar_kws={"orientation": "horizontal"},   # 是否横向显示图例色带
                #square = True,     # 是否正方形显示图表
               )
    sns.set(style="white")
    # 设置风格
    
    rs = np.random.RandomState(33)
    d = pd.DataFrame(rs.normal(size=(100, 26)))
    corr = d.corr()   # 求解相关性矩阵表格
    # 创建数据
    
    mask = np.zeros_like(corr, dtype=np.bool)
    mask[np.triu_indices_from(mask)] = True
    # 设置一个“上三角形”蒙版
    
    cmap = sns.diverging_palette(220, 10, as_cmap=True)
    # 设置调色盘
    
    sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,
                square=True, linewidths=0.2)
    # 生成半边热图

    六 结构化图表可视化 

      sns.FacetGrid()

    >>> g = sns.FacetGrid(tips, col="time",  hue="smoker")
    >>> g = (g.map(plt.scatter, "total_bill", "tip", edgecolor="w")
    ...       .add_legend())

  • 相关阅读:
    廖雪峰的多线程 1
    保持良好的心态 戒骄戒躁
    Break camelCase
    int32 to IPv4 (int32到IPv4地址转换)
    Stop gninnipS My sdroW!
    Find The Parity Outlier 找到奇偶校验异常值
    今日新闻整理 2020-7-31
    改造rabbitmq demo 到 jpa
    Flink实战(110):FLINK-SQL应用场景(11)connector(十九)Flink 与 hive 结合使用(七) Flink Hive Connector 使用
    Hadoop基础(六十):面试题 Hadoop数据切片(二)切片机制源码
  • 原文地址:https://www.cnblogs.com/654321cc/p/11929578.html
Copyright © 2020-2023  润新知