32.md 13.2 KB
Newer Older
W
init  
wizardforcel 已提交
1 2
# seaborn.FacetGrid

W
credit  
wizardforcel 已提交
3 4
> 译者:[hyuuo](https://github.com/hyuuo)

W
init  
wizardforcel 已提交
5 6 7 8
```py
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)
```

落晓o's avatar
落晓o 已提交
9
用于绘制条件关系的多图网格。
W
init  
wizardforcel 已提交
10 11 12 13 14

```py
__init__(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)
```

W
wizardforcel 已提交
15
初始化 matplotlib 画布和 FacetGrid 对象。
W
init  
wizardforcel 已提交
16

落晓o's avatar
落晓o 已提交
17
该类将数据集映射到由行和列组成的网格中的多个轴上,这些轴与数据集中变量的级别对应。它产生的图通常被称为“lattice”,“trellis”或“small-multiple”图形。
W
init  
wizardforcel 已提交
18

落晓o's avatar
落晓o 已提交
19
它还可以用`hue`参数表示第三个变量的级别,该参数绘制不同颜色的不同数据子集。它使用颜色来解析第三维度上的元素,但是只绘制相互重叠的子集,并且不会像接受“hue”的坐标轴级函数那样为特定的可视化定制“hue”参数。
W
init  
wizardforcel 已提交
20

W
wizardforcel 已提交
21
当使用从数据集推断语义映射的 seaborn 函数时,必须注意在各个方面之间同步这些映射。在大多数情况下,使用图形级函数(例如[`relplot()`](seaborn.relplot.html#seaborn.relplot "seaborn.relplot")[`catplot()`](seaborn.catplot.html#seaborn.catplot "seaborn.catplot"))比直接使用[`FacetGrid`](seaborn.FacetGrid.html#seaborn.FacetGrid "seaborn.FacetGrid")更好。
W
init  
wizardforcel 已提交
22

W
wizardforcel 已提交
23
基本工作流程是使用数据集和用于构造网格的变量初始化 FacetGrid 对象。然后,通过调用[`FacetGrid.map()`](seaborn.FacetGrid.map.html#seaborn.FacetGrid.map "seaborn.FacetGrid.map")[`FacetGrid.map_dataframe()`](seaborn.FacetGrid.map_dataframe.html#seaborn.FacetGrid.map_dataframe "seaborn.FacetGrid.map_dataframe"),可以将一个或多个绘图函数应用于每个子集。最后,可以使用其他方法调整绘图,以执行更改轴标签、使用不同刻度或添加图例等操作。有关详细信息,请参阅下面的详细代码示例。
W
init  
wizardforcel 已提交
24

沈宇 已提交
25
更多相关信息请参阅[`教程`](http://seaborn.pydata.org/tutorial/axis_grids.html#grid-tutorial)
W
init  
wizardforcel 已提交
26

W
wizardforcel 已提交
27
参数:`data`:DataFrame 数据。
W
init  
wizardforcel 已提交
28

W
wizardforcel 已提交
29
> 整洁的(“长形式”)dataframe 数据,其中每一列是一个变量,每一行是一个观察实例。
W
init  
wizardforcel 已提交
30

落晓o's avatar
落晓o 已提交
31
`row, col, hue`:字符串。
W
init  
wizardforcel 已提交
32

落晓o's avatar
落晓o 已提交
33
> 定义数据子集的变量,这些变量将在网格的不同方面绘制。请参阅`*_order`参数以控制此变量的级别顺序。
W
init  
wizardforcel 已提交
34

落晓o's avatar
落晓o 已提交
35
`col_wrap`:整形数值,可选参数。
W
init  
wizardforcel 已提交
36

落晓o's avatar
落晓o 已提交
37
> 以此参数值来限制网格的列维度,以便列面跨越多行。与`row`面不兼容。
W
init  
wizardforcel 已提交
38

落晓o's avatar
落晓o 已提交
39
`share{x,y}`:布尔值,'col' 或 'row'可选
W
init  
wizardforcel 已提交
40

W
wizardforcel 已提交
41
> 如果为 true,则跨列共享 y 轴或者跨行共享 x 轴。
W
init  
wizardforcel 已提交
42

落晓o's avatar
落晓o 已提交
43
`height`:标量,可选参数。
W
init  
wizardforcel 已提交
44

落晓o's avatar
落晓o 已提交
45
> 每个图片的高度设定(以英寸为单位)。另见:*aspect*
W
init  
wizardforcel 已提交
46

落晓o's avatar
落晓o 已提交
47
`aspect`:标量,可选参数。
W
init  
wizardforcel 已提交
48

W
wizardforcel 已提交
49
> 每个图片的纵横比,因此 aspect * height 给出每个图片的宽度,单位为英寸。
W
init  
wizardforcel 已提交
50

落晓o's avatar
落晓o 已提交
51
`palette`:调色板名称,列表或字典,可选参数。
W
init  
wizardforcel 已提交
52

W
wizardforcel 已提交
53
> 用于色调变量的不同级别的颜色。应为[`color_palette()`](seaborn.color_palette.html#seaborn.color_palette "seaborn.color_palette")可以解释的参数,或者是将色调级别映射到 matplotlib 颜色的字典。
W
init  
wizardforcel 已提交
54

落晓o's avatar
落晓o 已提交
55
`{row,col,hue}_order`:列表,可选参数。
W
init  
wizardforcel 已提交
56

W
wizardforcel 已提交
57
> 对所给命令级别进行排序。默认情况下,这将是在数据中显示的级别,或者,如果变量是 pandas 分类,则为类别顺序。
W
init  
wizardforcel 已提交
58

落晓o's avatar
落晓o 已提交
59
`hue_kws`:参数-列表值的映射字典
W
init  
wizardforcel 已提交
60

落晓o's avatar
落晓o 已提交
61
> 插入到绘图调用中的其他关键字参数,使得其他绘图属性在色调变量的级别上有所不同(例如散点图中的标记)。
W
init  
wizardforcel 已提交
62

落晓o's avatar
落晓o 已提交
63
`legend_out`:布尔值,可选参数。
W
init  
wizardforcel 已提交
64

W
wizardforcel 已提交
65
> 如果为 True,则图形尺寸将被扩展,图例将绘制在中间右侧的图形之外。
W
init  
wizardforcel 已提交
66

落晓o's avatar
落晓o 已提交
67
`despine`:布尔值,可选参数。
W
init  
wizardforcel 已提交
68

落晓o's avatar
落晓o 已提交
69
> 从图中移除顶部和右侧边缘框架。
W
init  
wizardforcel 已提交
70

落晓o's avatar
落晓o 已提交
71
`margin_titles`:布尔值,可选参数。
W
init  
wizardforcel 已提交
72

W
wizardforcel 已提交
73
> 如果为 True,则行变量的标题将绘制在最后一列的右侧。此选项是实验性的,可能无法在所有情况下使用。
W
init  
wizardforcel 已提交
74

落晓o's avatar
落晓o 已提交
75
`{x, y}lim`:元组,可选参数。
W
init  
wizardforcel 已提交
76

W
wizardforcel 已提交
77
> 每个图片上每个轴的限制(仅当 share {x,y}为 True 时才相关)。
W
init  
wizardforcel 已提交
78

落晓o's avatar
落晓o 已提交
79
`subplot_kws`:字典,可选参数。
W
init  
wizardforcel 已提交
80

W
wizardforcel 已提交
81
> 传递给 matplotlib subplot(s)方法的关键字参数字典。
W
init  
wizardforcel 已提交
82

落晓o's avatar
落晓o 已提交
83
`gridspec_kws`:字典,可选参数。
W
init  
wizardforcel 已提交
84

W
wizardforcel 已提交
85
> 传递给 matplotlib 的`gridspec`模块(通过`plt.subplots`)的关键字参数字典。需要 matplotlib> = 1.4,如果`col_wrap`不是`None`,则忽略它。
W
init  
wizardforcel 已提交
86

落晓o's avatar
落晓o 已提交
87
**另请参见**
W
wizardforcel 已提交
88

落晓o's avatar
落晓o 已提交
89
用于绘制成对关系的子图网格。
W
init  
wizardforcel 已提交
90

落晓o's avatar
落晓o 已提交
91
[`relplot`](#seaborn.relplot "seaborn.relplot")
W
init  
wizardforcel 已提交
92

落晓o's avatar
落晓o 已提交
93
结合关系图和[`FacetGrid`](#seaborn.FacetGrid "seaborn.FacetGrid")
W
init  
wizardforcel 已提交
94

落晓o's avatar
落晓o 已提交
95
[`catplot`](#seaborn.catplot "seaborn.catplot")
W
init  
wizardforcel 已提交
96

落晓o's avatar
落晓o 已提交
97 98 99 100 101 102 103 104
结合分类图和[`FacetGrid`](#seaborn.FacetGrid "seaborn.FacetGrid")

[`lmplot`](#seaborn.lmplot "seaborn.lmplot")

结合回归图和[`FacetGrid`](#seaborn.FacetGrid "seaborn.FacetGrid")

范例

W
wizardforcel 已提交
105
使用 tips 数据集初始化 2x2 网格图:
W
init  
wizardforcel 已提交
106 107 108 109 110 111 112 113 114 115

```py
>>> import seaborn as sns; sns.set(style="ticks", color_codes=True)
>>> tips = sns.load_dataset("tips")
>>> g = sns.FacetGrid(tips, col="time", row="smoker")

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-1.png](img/b8699392ad92687d3ac264d00b00ec9b.jpg)

落晓o's avatar
落晓o 已提交
116
在每个子图绘制一个单变量图:
W
init  
wizardforcel 已提交
117 118 119 120 121 122 123 124 125 126

```py
>>> import matplotlib.pyplot as plt
>>> g = sns.FacetGrid(tips, col="time",  row="smoker")
>>> g = g.map(plt.hist, "total_bill")

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-2.png](img/ee99e47d6e0d2262037bca2e7fdb9772.jpg)

W
wizardforcel 已提交
127
(注意,没有必要重新捕获返回的变量;它是相同的对象,但在示例中这样做使得处理 doctests 更加方便)。
W
init  
wizardforcel 已提交
128

落晓o's avatar
落晓o 已提交
129
将其他关键字参数传递给映射函数:
W
init  
wizardforcel 已提交
130 131 132 133 134 135 136 137 138 139 140

```py
>>> import numpy as np
>>> bins = np.arange(0, 65, 5)
>>> g = sns.FacetGrid(tips, col="time",  row="smoker")
>>> g = g.map(plt.hist, "total_bill", bins=bins, color="r")

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-3.png](img/7bd763d402e774603d6f5e7c48c2369a.jpg)

落晓o's avatar
落晓o 已提交
141
在每个子图绘制一个双变量函数:
W
init  
wizardforcel 已提交
142 143 144 145 146 147 148 149 150

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

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-4.png](img/2aca4924009e92a55bc1579fc086d36c.jpg)

落晓o's avatar
落晓o 已提交
151
将其中一个变量分配给绘图元素的颜色:
W
init  
wizardforcel 已提交
152 153 154 155 156 157 158 159 160 161

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

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-5.png](img/c53a49f5b838d50776627fc8910138ce.jpg)

落晓o's avatar
落晓o 已提交
162
更改每个子图的高度和纵横比:
W
init  
wizardforcel 已提交
163 164 165 166 167 168 169 170 171

```py
>>> g = sns.FacetGrid(tips, col="day", height=4, aspect=.5)
>>> g = g.map(plt.hist, "total_bill", bins=bins)

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-6.png](img/ca19289fa3db7f35bf27fa3f09db128e.jpg)

落晓o's avatar
落晓o 已提交
172
指定绘图元素的顺序:
W
init  
wizardforcel 已提交
173 174 175 176 177 178 179 180 181

```py
>>> g = sns.FacetGrid(tips, col="smoker", col_order=["Yes", "No"])
>>> g = g.map(plt.hist, "total_bill", bins=bins, color="m")

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-7.png](img/d84004bd86dc3645488324a3fbb3b060.jpg)

落晓o's avatar
落晓o 已提交
182
使用不同的调色板:
W
init  
wizardforcel 已提交
183 184 185 186 187 188 189 190 191 192 193 194

```py
>>> kws = dict(s=50, linewidth=.5, edgecolor="w")
>>> g = sns.FacetGrid(tips, col="sex", hue="time", palette="Set1",
...                   hue_order=["Dinner", "Lunch"])
>>> g = (g.map(plt.scatter, "total_bill", "tip", **kws)
...      .add_legend())

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-8.png](img/fe9b97ad8c3e66c3a2514249fcd62ee6.jpg)

落晓o's avatar
落晓o 已提交
195
使用字典将色调级别映射到颜色:
W
init  
wizardforcel 已提交
196 197 198 199 200 201 202 203 204 205 206 207

```py
>>> pal = dict(Lunch="seagreen", Dinner="gray")
>>> g = sns.FacetGrid(tips, col="sex", hue="time", palette=pal,
...                   hue_order=["Dinner", "Lunch"])
>>> g = (g.map(plt.scatter, "total_bill", "tip", **kws)
...      .add_legend())

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-9.png](img/9299602c8a3b49e2a9095ad9ea69f07f.jpg)

落晓o's avatar
落晓o 已提交
208
另外,为色调级别使用不同的标记:
W
init  
wizardforcel 已提交
209 210 211 212 213 214 215 216 217 218 219 220

```py
>>> g = sns.FacetGrid(tips, col="sex", hue="time", palette=pal,
...                   hue_order=["Dinner", "Lunch"],
...                   hue_kws=dict(marker=["^", "v"]))
>>> g = (g.map(plt.scatter, "total_bill", "tip", **kws)
...      .add_legend())

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-10.png](img/92494d907a4bd738426ff755349e4992.jpg)

落晓o's avatar
落晓o 已提交
221
将包含多个级别的列变量“换行”到行中:
W
init  
wizardforcel 已提交
222 223 224 225 226 227 228 229 230 231

```py
>>> att = sns.load_dataset("attention")
>>> g = sns.FacetGrid(att, col="subject", col_wrap=5, height=1.5)
>>> g = g.map(plt.plot, "solutions", "score", marker=".")

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-11.png](img/3a3de5e84041d929dbf5cbade67f93e6.jpg)

落晓o's avatar
落晓o 已提交
232
定义一个自定义双变量函数来映射到网格:
W
init  
wizardforcel 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247

```py
>>> from scipy import stats
>>> def qqplot(x, y, **kwargs):
...     _, xr = stats.probplot(x, fit=False)
...     _, yr = stats.probplot(y, fit=False)
...     plt.scatter(xr, yr, **kwargs)
>>> g = sns.FacetGrid(tips, col="smoker", hue="sex")
>>> g = (g.map(qqplot, "total_bill", "tip", **kws)
...       .add_legend())

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-12.png](img/a84563a49e5578ddeff33795280887f1.jpg)

落晓o's avatar
落晓o 已提交
248
定义一个使用`DataFrame`对象的自定义函数,并接受列名作为位置变量:
W
init  
wizardforcel 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

```py
>>> import pandas as pd
>>> df = pd.DataFrame(
...     data=np.random.randn(90, 4),
...     columns=pd.Series(list("ABCD"), name="walk"),
...     index=pd.date_range("2015-01-01", "2015-03-31",
...                         name="date"))
>>> df = df.cumsum(axis=0).stack().reset_index(name="val")
>>> def dateplot(x, y, **kwargs):
...     ax = plt.gca()
...     data = kwargs.pop("data")
...     data.plot(x=x, y=y, ax=ax, grid=False, **kwargs)
>>> g = sns.FacetGrid(df, col="walk", col_wrap=2, height=3.5)
>>> g = g.map_dataframe(dateplot, "date", "val")

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-13.png](img/2017a8a703bdcc077baea030a758721d.jpg)

落晓o's avatar
落晓o 已提交
269
绘图后使用不同的轴标签:
W
init  
wizardforcel 已提交
270 271 272 273 274 275 276 277 278 279

```py
>>> g = sns.FacetGrid(tips, col="smoker", row="sex")
>>> g = (g.map(plt.scatter, "total_bill", "tip", color="g", **kws)
...       .set_axis_labels("Total bill (US Dollars)", "Tip"))

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-14.png](img/52d5efab2c08ec72873b3e66fea66d14.jpg)

落晓o's avatar
落晓o 已提交
280
设置每个子图共享的其他属性:
W
init  
wizardforcel 已提交
281 282 283 284 285 286 287 288 289 290 291

```py
>>> g = sns.FacetGrid(tips, col="smoker", row="sex")
>>> g = (g.map(plt.scatter, "total_bill", "tip", color="r", **kws)
...       .set(xlim=(0, 60), ylim=(0, 12),
...            xticks=[10, 30, 50], yticks=[2, 6, 10]))

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-15.png](img/308a2f3dd32f77b25254d6650cce7be8.jpg)

落晓o's avatar
落晓o 已提交
292
为子图标题使用不同的模板:
W
init  
wizardforcel 已提交
293 294 295 296 297 298 299 300 301 302

```py
>>> g = sns.FacetGrid(tips, col="size", col_wrap=3)
>>> g = (g.map(plt.hist, "tip", bins=np.arange(0, 13), color="c")
...       .set_titles("{col_name} diners"))

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-16.png](img/b68bba1b9871f75b818870d08a9e3523.jpg)

落晓o's avatar
落晓o 已提交
303
收紧每个子图:
W
init  
wizardforcel 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316

```py
>>> g = sns.FacetGrid(tips, col="smoker", row="sex",
...                   margin_titles=True)
>>> g = (g.map(plt.scatter, "total_bill", "tip", color="m", **kws)
...       .set(xlim=(0, 60), ylim=(0, 12),
...            xticks=[10, 30, 50], yticks=[2, 6, 10])
...       .fig.subplots_adjust(wspace=.05, hspace=.05))

```

![http://seaborn.pydata.org/_images/seaborn-FacetGrid-17.png](img/30bd1c7aa657fabb90851a094c8d0a1e.jpg)

落晓o's avatar
落晓o 已提交
317 318
方法

W
wizardforcel 已提交
319
| [`__init__`](#seaborn.FacetGrid.__init__ "seaborn.FacetGrid.__init__")(data[, row, col, hue, col_wrap, …]) | 初始化 matplotlib 画布和 FacetGrid 对象。 |
落晓o's avatar
落晓o 已提交
320 321 322 323 324 325 326 327 328 329 330

| `add_legend`([legend_data, title, label_order]) | 绘制一个图例,可能将其放在轴外并调整图形大小。|

| `despine`(\**kwargs) | 从子图中移除轴的边缘框架。 |

| `facet_axis`(row_i, col_j) | 使这些索引识别的轴处于活动状态并返回。 |

| `facet_data`() | 用于每个子图的名称索引和数据子集的生成器。 |

| [`map`](seaborn.FacetGrid.map.html#seaborn.FacetGrid.map "seaborn.FacetGrid.map")(func, *args, \**kwargs) | 将绘图功能应用于每个子图的数据子集。 |

W
wizardforcel 已提交
331
| [`map_dataframe`](seaborn.FacetGrid.map_dataframe.html#seaborn.FacetGrid.map_dataframe "seaborn.FacetGrid.map_dataframe")(func, *args, \**kwargs) | 像`.map`一样,但是将 args 作为字符串传递并在 kwargs 中插入数据。 |
落晓o's avatar
落晓o 已提交
332 333 334 335 336 337 338

| `savefig`(*args, \**kwargs) | 保存图片。 |

| `set`(\**kwargs) | 在每个子图集坐标轴上设置属性。|

| `set_axis_labels`([x_var, y_var]) | 在网格的左列和底行设置轴标签。 |

落晓o's avatar
落晓o 已提交
339
| `set_titles`([template, row_template, …]) | 在每个子图上方或网格边缘绘制标题。 |
落晓o's avatar
落晓o 已提交
340

W
wizardforcel 已提交
341
| `set_xlabels`([label]) | 在网格的底行标记 x 轴。 |
落晓o's avatar
落晓o 已提交
342

W
wizardforcel 已提交
343
| `set_xticklabels`([labels, step]) | 在网格的底行设置 x 轴刻度标签。 |
落晓o's avatar
落晓o 已提交
344

W
wizardforcel 已提交
345
| `set_ylabels`([label]) | 在网格的左列标记 y 轴。 |
落晓o's avatar
落晓o 已提交
346

W
wizardforcel 已提交
347
| `set_yticklabels`([labels]) | 在网格的左列上设置 y 轴刻度标签。 |
落晓o's avatar
落晓o 已提交
348 349 350 351

属性

| `ax` | 轻松访问单个坐标轴。 |