5-6 可视化库Seaborn-Facetgrid使用和绘制多变量

 

基本工作流程是FacetGrid使用数据集和用于构造网格的变量初始化对象。然后,可以通过调用FacetGrid.map()或将一个或多个绘图函数应用于每个子集 FacetGrid.map_dataframe()。最后,可以使用其他方法调整绘图,以执行更改轴标签,使用不同刻度或添加图例等操作

当使用从数据集推断语义映射的seaborn函数时,必须注意在各个方面之间同步这些映射。在大多数情况下,使用图形级别功能(例如relplot()或catplot())比 FacetGrid直接使用更好

参数:

*class seaborn.FacetGrid(data, row=None, col=None, hue=None, col_wrap=None, sharex=True, sharey=True, height=3, aspect=1, palette=None, row_order=None, col_order=None, hue_order=None, hue_kws=None, dropna=True, legend_out=True, despine=True, margin_titles=False, xlim=None, ylim=None, subplot_kws=None, gridspec_kws=None, size=None)

变量 解释 参数
data 处理后的(“长格式”)dataframe数据,其中每一列都是一个变量(特征),每一行都是一个样本 DataFrame
row, col, hue 定义数据子集的变量,这些变量将在网格的不同方面绘制。请参阅下面*_order参数以控制该变量的级别顺序 strings
col_wrap 这个意思是图网格列维度限制 int, optional
share{x,y} 是否共享x轴或者y轴,就是说如果为真,就共享同一个轴,否则就不共享,默认是都共享,即都为True bool, ‘col’, or ‘row’ optional
height 每个图片的高度设定,默认为3 scalar, optional
aspect 文档说是纵横比,是说每个小图的横轴长度和纵轴的比 scalar, optional
palette 这个简单,一般在使用hue时来改变颜色的,有这几种系统给的可选deep, muted, bright, pastel, dark, colorblind palette name, list, or dict, optional
{row,col,hue}_order 对所给命令的级别进行排序。默认情况下,这将是数据中显示的级别,如果变量是pandas分类,则是类别顺序。 lists, optional
hue_kws 其他关键字参数插入到绘图调用中,让其他绘图属性在色相变量的级别上有所不同(例如散点图中的标记)hue_kws=dict(marker=["^", "v"])) # 给颜色语意使用不同的标签, dictionary of param -> list of values mapping
legend_out 默认为True,legend是图例的意思,如果True,图形尺寸将被扩展,并且图例将被绘制在中心右侧的图形之外,为False时,图例单独放出来 bool, optional
despine 从图中移除顶部和右侧脊柱,就是边缘框架 boolean, optional
margin_titles 如果是真的,那么行变量的标题就会被绘制到最后一列的右边。这个选项是实验性的,在所有情况下都可能不起作用。 bool, optional
{x, y}lim 每个方面的每个轴的限制(只有当共享x时才相关,y是正确的 tuples, optional
subplot_kws 传递给matplotlib的subplot(s) 方法的关键字参数字典Dictionary of keyword arguments passed to matplotlib subplot(s) methods.这个需要看看subplot函数的参数,后面有时间补上 dict, optional
gridspec_kws 传递给matplotlib的gridspec模块的关键字参数的字典(Via plt.subplots)。matplotlib >= 1.4,如果colwrap不是None,则会被忽略 dict, optional
In [1]:
%matplotlib inline
import numpy as np
import pandas as pd
from scipy import stats,integrate
import matplotlib.pyplot as plt
import seaborn as sns
np.random.seed(sum(map(ord,"axis_grids")))
In [2]:
tips=sns.load_dataset("tips")
tips.head()
Out[2]:
 
  total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
 

1.实例化对象g,并有map函数绘图

In [3]:
g=sns.FacetGrid(tips,col="time")#FacetGrid当您想要在数据集的子集中分别可视化变量的分布或多个变量之间的关系时,该类非常有用
 
 
  • 直方图
In [4]:
g=sns.FacetGrid(tips,col="time")#先给图占位置
g.map(plt.hist,"tip")#作图
Out[4]:
<seaborn.axisgrid.FacetGrid at 0xadda9b0>
 
 
  • 散点图
In [5]:
g=sns.FacetGrid(tips,col="sex",hue="smoker")#先给图占位置
g.map(plt.scatter,"total_bill","tip",alpha=0.7)#作图,定义透明程度
g.add_legend()
Out[5]:
<seaborn.axisgrid.FacetGrid at 0xaddafd0>
 
 
  • row,col定义画出多个子图
  • regplot绘制回归图,定义fit_reg是否绘制回归线条,x_jitter或y_jitter定义指定轴的浮动系数
In [6]:
g=sns.FacetGrid(tips,row="smoker",col="time",margin_titles=True)#margin_titles=True,显示边上的title
g.map(sns.regplot,"size","total_bill",color=".1",fit_reg=False,x_jitter=.1)#fit_reg=False,x_jitter=.1。分别是指拟合回归大小指定系数
Out[6]:
<seaborn.axisgrid.FacetGrid at 0xafab0f0>
 
 
  • size大小和aspect长宽比
In [7]:
g=sns.FacetGrid(tips,col="day",size=4,aspect=0.5)
g.map(sns.barplot,"sex","total_bill")
 
E:\Software\Anaconda3_5.2.0\lib\site-packages\seaborn\axisgrid.py:703: UserWarning: Using the barplot function without specifying `order` is likely to produce an incorrect plot.
  warnings.warn(warning)
Out[7]:
<seaborn.axisgrid.FacetGrid at 0xaf51e80>
 
 
  1. pandas.Categorical(values, categories=None, ordered=None, dtype=None, fastpath=False)#对数据分类,Categorical是一种数据类型, ordered可以定义顺序
In [8]:
from pandas import  Categorical
ordered_days=tips.day.value_counts().index
print(ordered_days)
#order_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")
 
CategoricalIndex(['Sat', 'Sun', 'Thur', 'Fri'], categories=['Thur', 'Fri', 'Sat', 'Sun'], ordered=False, dtype='category')
 
E:\Software\Anaconda3_5.2.0\lib\site-packages\seaborn\axisgrid.py:703: UserWarning: Using the boxplot function without specifying `order` is likely to produce an incorrect plot.
  warnings.warn(warning)
Out[8]:
<seaborn.axisgrid.FacetGrid at 0xb0a26a0>
 
 
  • FacetGrid的 palette指定类别的颜色
In [9]:
pal=dict(Lunch="seagreen",Dinner="gray")#指定,palette颜色
#palette参数,一般在使用hue时来改变颜色的,有这几种系统给的可选deep, muted, bright, pastel, dark, colorblind
g=sns.FacetGrid(tips,hue="time",palette=pal,size=5)
g.map(plt.scatter,"total_bill","tip",s=50,alpha=0.6,linewidth=0.5,edgecolor="white")#s=>size,edgecolor=>颜色
g.add_legend()
Out[9]:
<seaborn.axisgrid.FacetGrid at 0xb83f588>
 
 
  • FacetGrid的 marker的形状及坐标范围指定
In [10]:
g = sns.FacetGrid(tips, hue='sex', palette='Set1', size=5, hue_kws={"marker":["^","v"]})
#g = sns.FacetGrid(tips, hue='sex',palette='Set1',size = 5, hue_kws={"marker":["^","v"]})
g.map(plt.scatter,"total_bill","tip",s=100,linewidth=0.5,edgecolor="white")
g.add_legend()#马如蛟,15185176184,机械工程学院
Out[10]:
<seaborn.axisgrid.FacetGrid at 0xbcaa0f0>
 
 
  • 轴的名字和子图和子图之间的间隔设置
In [11]:
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 = 0.5)
g.set_axis_labels("Total_bill(US Dollars)",'Tip')#轴的名字
g.set(xticks = [10,30,50], yticks =[2,6,10])#x,y轴的刻度
g.fig.subplots_adjust(wspace=.02,hspace=.02)#子图和子图之间的间隔设置
#g.fig.subplots_adjust():left,right,top,bottom,wspace,hspace可以设置这几个位置的间距
plt.show()
 
 

PairGrid绘图

In [12]:
iris = sns.load_dataset('iris')
g = sns.PairGrid(iris)
g.map(plt.scatter,s = 20, edgecolor = 'black')
plt.show()
 
 

3-1 指定绘图样式

In [13]:
g = sns.PairGrid(iris)
g.map_diag(plt.hist,edgecolor = 'black')#对角线上图片
g.map_offdiag(plt.scatter,s = 20, edgecolor = 'black')#非对角线上图片
plt.show()
 
 

3-2 增加分类

In [14]:
g = sns.PairGrid(iris,hue= 'species')
g.map_diag(plt.hist,edgecolor = 'black')#对角线上图片
g.map_offdiag(plt.scatter,s = 20, edgecolor = 'black')#非对角线上图片
g.add_legend()
plt.show()
 
 

3-3 指定绘制量

In [15]:
g = sns.PairGrid(iris, vars=['sepal_length','sepal_width'],hue = 'species')
g.map(plt.scatter,s = 20, edgecolor = 'black')
plt.show()
 
 

3-4 颜色绘制

In [16]:
g = sns.PairGrid(tips, hue = 'size', palette='GnBu_d')
g.map(plt.scatter, s = 50, edgecolor = 'white')
g.add_legend()
plt.show()
 

猜你喜欢

转载自www.cnblogs.com/AI-robort/p/11767751.html
5-6