Seaborn結構化圖形繪制(FacetGrid)


結構化圖形繪制(FacetGrid)

可實現多行多列個性化繪制圖形。

sns.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,
)
Docstring:      Multi-plot grid for plotting conditional relationships.
Init docstring:
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. :func:`relplot` or :func:`catplot`) than to use
:class:`FacetGrid` directly.

The basic workflow is to initialize the :class:`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
:meth:`FacetGrid.map` or :meth:`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 :ref:`tutorial <grid_tutorial>` for more information.

Parameters
----------
data : DataFrame
    Tidy ("long-form") dataframe where each column is a variable and each
    row is an observation.    
row, col, hue : strings
    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.
col_wrap : int, optional
    "Wrap" the column variable at this width, so that the column facets
    span multiple rows. Incompatible with a ``row`` facet.    
share{x,y} : bool, 'col', or 'row' optional
    If true, the facets will share y axes across columns and/or x axes
    across rows.    
height : scalar, optional
    Height (in inches) of each facet. See also: ``aspect``.    
aspect : scalar, optional
    Aspect ratio of each facet, so that ``aspect * height`` gives the width
    of each facet in inches.    
palette : palette name, list, or dict, optional
    Colors to use for the different levels of the ``hue`` variable. Should
    be something that can be interpreted by :func:`color_palette`, or a
    dictionary mapping hue levels to matplotlib colors.    
{row,col,hue}_order : lists, optional
    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.
hue_kws : dictionary of param -> list of values mapping
    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).
legend_out : bool, optional
    If ``True``, the figure size will be extended, and the legend will be
    drawn outside the plot on the center right.    
despine : boolean, optional
    Remove the top and right spines from the plots.
margin_titles : bool, optional
    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.
subplot_kws : dict, optional
    Dictionary of keyword arguments passed to matplotlib subplot(s)
    methods.
gridspec_kws : dict, optional
    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``.

See Also
--------
PairGrid : Subplot grid for plotting pairwise relationships.
relplot : Combine a relational plot and a :class:`FacetGrid`.
catplot : Combine a categorical plot and a :class:`FacetGrid`.
lmplot : Combine a regression plot and a :class:`FacetGrid`.
#導入數據
tips = sns.load_dataset('tips', data_home='./seaborn-data')
tips

#設置風格
sns.set_style('white')
#col設置網格的分類列,row設置分類行
ax = sns.FacetGrid(tips, col='time', row='sex')

散點圖

ax = sns.FacetGrid(tips, col='time', row='sex')
#利用map方法在網格內繪制散點圖sns.scatterplot = plt.scatter,sns的散點圖更美觀
ax = ax.map(sns.scatterplot, 'total_bill', 'tip')

#hue設置分類繪制
ax = sns.FacetGrid(tips, col='time', hue='sex')
ax = ax.map(sns.scatterplot, 'total_bill', 'tip')
#添加圖例
ax = ax.add_legend()

#定義一個文本函數
def annotate(data, **kws):
    n = len(data)
    ax = plt.gca()
    ax.text(.1, .6, f"N={n}", transform=ax.transAxes)
    
ax = sns.FacetGrid(tips, col='time')
ax = ax.map(sns.scatterplot, 'total_bill', 'tip')
#添加文本標簽
ax = ax.map_dataframe(annotate)

#其它參數
#margin_titles設置邊緣標頭
ax = sns.FacetGrid(tips, col='sex', row='time', margin_titles=True)
ax.map(sns.scatterplot, 'total_bill', 'tip')
#set_axis_labels設置x軸和y軸標簽
ax.set_axis_labels('Totall bill($)', 'Tip($)')
#set_titles設置標頭(會出現重疊現象)
ax.set_titles(col_template='{col_name} patrons', row_template='{row_name}')
#坐標上下限和刻度設置
ax.set(xlim=(0,60), ylim=(0, 12), xticks=[10, 30, 50], yticks=[2, 6, 10])
#存儲圖片
ax.savefig('facet_plot.png')

#despine設置是否顯示上和右邊框線
ax = sns.FacetGrid(tips, col='sex', row='time', margin_titles=True, despine=False)
ax.map(sns.scatterplot, 'total_bill', 'tip')
#設置圖形間隔
ax.fig.subplots_adjust(wspace=0, hspace=0)

#QQ圖:檢驗樣本數據概率分布(例如正態分布)的方法,直觀的表示觀測值與預測值之間的差異,或兩個數之間的差異
from scipy import stats
#定義QQ圖函數
def qqplot(x, y, **kwargs):
    _, xr = stats.probplot(x, fit=False)         #擬合概率圖
    _, yr = stats.probplot(y, fit=False)
    sns.scatterplot(xr, yr, **kwargs)            #**kwargs表示關鍵字參數,可以用字典形式傳入參數
    
g = sns.FacetGrid(tips, col='smoker', hue='sex')
g = g.map(qqplot, 'total_bill', 'tip')
g = g.add_legend()

直方圖

#直方圖
g = sns.FacetGrid(tips, col='time', row='smoker')
g = g.map(plt.hist, 'total_bill')

#bins設置直方圖個數,color設置顏色
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')

#height設置高度,aspece設寬高比
bins = np.arange(0, 65, 5)
g = sns.FacetGrid(tips, col='time', row='smoker', height=4, aspect=.5)
g = g.map(plt.hist, 'total_bill', bins=bins, color='r')

#col_order設置顯示順序
bins = np.arange(0, 65, 5)
g = sns.FacetGrid(tips, col='smoker', col_order=['Yea', 'No'])
g = g.map(plt.hist, 'total_bill', bins=bins, color='m')

直方密度圖

#直方密度圖
g = sns.FacetGrid(tips, col='time', row='smoker')
g = g.map(sns.distplot, 'total_bill')

折線圖

#導入數據
att = sns.load_dataset('attention', data_home='./seaborn-data')
#col_wrap設置列數,height設置高度,marker設置標記點樣式
g = sns.FacetGrid(att, col='subject', col_wrap=5, height=1.5)
g = g.map(plt.plot, 'solutions', 'score', marker='.')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM