32.md 13.4 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# seaborn.FacetGrid

```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)
```

Multi-plot grid for plotting conditional relationships.

```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)
```

Initialize the matplotlib figure and FacetGrid object.

This class maps a dataset onto multiple axes arrayed in a grid of rows and columns that correspond to _levels_ of variables in the dataset. The plots it produces are often called “lattice”, “trellis”, or “small-multiple” graphics.

It can also represent levels of a third varaible with the `hue` parameter, which plots different subets of data in different colors. This uses color to resolve elements on a third dimension, but only draws subsets on top of each other and will not tailor the `hue` parameter for the specific visualization the way that axes-level functions that accept `hue` will.

When using seaborn functions that infer semantic mappings from a dataset, care must be taken to synchronize those mappings across facets. In most cases, it will be better to use a figure-level function (e.g. [`relplot()`](seaborn.relplot.html#seaborn.relplot "seaborn.relplot") or [`catplot()`](seaborn.catplot.html#seaborn.catplot "seaborn.catplot")) than to use [`FacetGrid`](#seaborn.FacetGrid "seaborn.FacetGrid") directly.

The basic workflow is to initialize the [`FacetGrid`](#seaborn.FacetGrid "seaborn.FacetGrid") object with the dataset and the variables that are used to structure the grid. Then one or more plotting functions can be applied to each subset by calling [`FacetGrid.map()`](seaborn.FacetGrid.map.html#seaborn.FacetGrid.map "seaborn.FacetGrid.map") or [`FacetGrid.map_dataframe()`](seaborn.FacetGrid.map_dataframe.html#seaborn.FacetGrid.map_dataframe "seaborn.FacetGrid.map_dataframe"). Finally, the plot can be tweaked with other methods to do things like change the axis labels, use different ticks, or add a legend. See the detailed code examples below for more information.

See the [tutorial](../tutorial/axis_grids.html#grid-tutorial) for more information.

W
wizardforcel 已提交
25
参数:`data`:DataFrame
W
init  
wizardforcel 已提交
26 27 28

> Tidy (“long-form”) dataframe where each column is a variable and each row is an observation.

W
wizardforcel 已提交
29
`row, col, hue`:strings
W
init  
wizardforcel 已提交
30 31 32

> Variables that define subsets of the data, which will be drawn on separate facets in the grid. See the `*_order` parameters to control the order of levels of this variable.

W
wizardforcel 已提交
33
`col_wrap`:int, optional
W
init  
wizardforcel 已提交
34 35 36

> “Wrap” the column variable at this width, so that the column facets span multiple rows. Incompatible with a `row` facet.

W
wizardforcel 已提交
37
`share{x,y}`:bool, ‘col’, or ‘row’ optional
W
init  
wizardforcel 已提交
38 39 40

> If true, the facets will share y axes across columns and/or x axes across rows.

W
wizardforcel 已提交
41
`height`:scalar, optional
W
init  
wizardforcel 已提交
42 43 44

> Height (in inches) of each facet. See also: `aspect`.

W
wizardforcel 已提交
45
`aspect`:scalar, optional
W
init  
wizardforcel 已提交
46 47 48

> Aspect ratio of each facet, so that `aspect * height` gives the width of each facet in inches.

W
wizardforcel 已提交
49
`palette`:palette name, list, or dict, optional
W
init  
wizardforcel 已提交
50 51 52

> Colors to use for the different levels of the `hue` variable. Should be something that can be interpreted by [`color_palette()`](seaborn.color_palette.html#seaborn.color_palette "seaborn.color_palette"), or a dictionary mapping hue levels to matplotlib colors.

W
wizardforcel 已提交
53
`{row,col,hue}_order`:lists, optional
W
init  
wizardforcel 已提交
54 55 56

> Order for the levels of the faceting variables. By default, this will be the order that the levels appear in `data` or, if the variables are pandas categoricals, the category order.

W
wizardforcel 已提交
57
`hue_kws`:dictionary of param -> list of values mapping
W
init  
wizardforcel 已提交
58 59 60

> Other keyword arguments to insert into the plotting call to let other plot attributes vary across levels of the hue variable (e.g. the markers in a scatterplot).

W
wizardforcel 已提交
61
`legend_out`:bool, optional
W
init  
wizardforcel 已提交
62 63 64

> If `True`, the figure size will be extended, and the legend will be drawn outside the plot on the center right.

W
wizardforcel 已提交
65
`despine`:boolean, optional
W
init  
wizardforcel 已提交
66 67 68

> Remove the top and right spines from the plots.

W
wizardforcel 已提交
69
`margin_titles`:bool, optional
W
init  
wizardforcel 已提交
70 71 72 73 74 75 76

> If `True`, the titles for the row variable are drawn to the right of the last column. This option is experimental and may not work in all cases.

**{x, y}lim: tuples, optional**

> Limits for each of the axes on each facet (only relevant when share{x, y} is True.

W
wizardforcel 已提交
77
`subplot_kws`:dict, optional
W
init  
wizardforcel 已提交
78 79 80

> Dictionary of keyword arguments passed to matplotlib subplot(s) methods.

W
wizardforcel 已提交
81
`gridspec_kws`:dict, optional
W
init  
wizardforcel 已提交
82 83 84

> Dictionary of keyword arguments passed to matplotlib’s `gridspec` module (via `plt.subplots`). Requires matplotlib >= 1.4 and is ignored if `col_wrap` is not `None`.

W
wizardforcel 已提交
85

W
init  
wizardforcel 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325

See also

Subplot grid for plotting pairwise relationships.Combine a relational plot and a [`FacetGrid`](#seaborn.FacetGrid "seaborn.FacetGrid").Combine a categorical plot and a [`FacetGrid`](#seaborn.FacetGrid "seaborn.FacetGrid").Combine a regression plot and a [`FacetGrid`](#seaborn.FacetGrid "seaborn.FacetGrid").

Examples

Initialize a 2x2 grid of facets using the tips dataset:

```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)

Draw a univariate plot on each facet:

```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)

(Note that it’s not necessary to re-catch the returned variable; it’s the same object, but doing so in the examples makes dealing with the doctests somewhat less annoying).

Pass additional keyword arguments to the mapped function:

```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)

Plot a bivariate function on each facet:

```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)

Assign one of the variables to the color of the plot elements:

```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)

Change the height and aspect ratio of each facet:

```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)

Specify the order for plot elements:

```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)

Use a different color palette:

```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)

Use a dictionary mapping hue levels to colors:

```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)

Additionally use a different marker for the hue levels:

```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)

“Wrap” a column variable with many levels into the rows:

```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)

Define a custom bivariate function to map onto the grid:

```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)

Define a custom function that uses a `DataFrame` object and accepts column names as positional variables:

```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)

Use different axes labels after plotting:

```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)

Set other attributes that are shared across the facetes:

```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)

Use a different template for the facet titles:

```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)

Tighten the facets:

```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)

Methods

| [`__init__`](#seaborn.FacetGrid.__init__ "seaborn.FacetGrid.__init__")(data[, row, col, hue, col_wrap, …]) | Initialize the matplotlib figure and FacetGrid object. |
| `add_legend`([legend_data, title, label_order]) | Draw a legend, maybe placing it outside axes and resizing the figure. |
| `despine`(**kwargs) | Remove axis spines from the facets. |
| `facet_axis`(row_i, col_j) | Make the axis identified by these indices active and return it. |
| `facet_data`() | Generator for name indices and data subsets for each facet. |
| [`map`](seaborn.FacetGrid.map.html#seaborn.FacetGrid.map "seaborn.FacetGrid.map")(func, *args, **kwargs) | Apply a plotting function to each facet’s subset of the data. |
| [`map_dataframe`](seaborn.FacetGrid.map_dataframe.html#seaborn.FacetGrid.map_dataframe "seaborn.FacetGrid.map_dataframe")(func, *args, **kwargs) | Like `.map` but passes args as strings and inserts data in kwargs. |
| `savefig`(*args, **kwargs) | Save the figure. |
| `set`(**kwargs) | Set attributes on each subplot Axes. |
| `set_axis_labels`([x_var, y_var]) | Set axis labels on the left column and bottom row of the grid. |
| `set_titles`([template, row_template, …]) | Draw titles either above each facet or on the grid margins. |
| `set_xlabels`([label]) | Label the x axis on the bottom row of the grid. |
| `set_xticklabels`([labels, step]) | Set x axis tick labels on the bottom row of the grid. |
| `set_ylabels`([label]) | Label the y axis on the left column of the grid. |
| `set_yticklabels`([labels]) | Set y axis tick labels on the left column of the grid. |

Attributes

| `ax` | Easy access to single axes. |