distributions.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. """Plotting functions for visualizing distributions."""
  2. import numpy as np
  3. from scipy import stats
  4. import pandas as pd
  5. import matplotlib as mpl
  6. import matplotlib.pyplot as plt
  7. import matplotlib.transforms as tx
  8. from matplotlib.collections import LineCollection
  9. import warnings
  10. try:
  11. import statsmodels.nonparametric.api as smnp
  12. _has_statsmodels = True
  13. except ImportError:
  14. _has_statsmodels = False
  15. from .utils import iqr, _kde_support, remove_na
  16. from .palettes import color_palette, light_palette, dark_palette, blend_palette
  17. __all__ = ["distplot", "kdeplot", "rugplot"]
  18. def _freedman_diaconis_bins(a):
  19. """Calculate number of hist bins using Freedman-Diaconis rule."""
  20. # From https://stats.stackexchange.com/questions/798/
  21. a = np.asarray(a)
  22. if len(a) < 2:
  23. return 1
  24. h = 2 * iqr(a) / (len(a) ** (1 / 3))
  25. # fall back to sqrt(a) bins if iqr is 0
  26. if h == 0:
  27. return int(np.sqrt(a.size))
  28. else:
  29. return int(np.ceil((a.max() - a.min()) / h))
  30. def distplot(a, bins=None, hist=True, kde=True, rug=False, fit=None,
  31. hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None,
  32. color=None, vertical=False, norm_hist=False, axlabel=None,
  33. label=None, ax=None):
  34. """Flexibly plot a univariate distribution of observations.
  35. This function combines the matplotlib ``hist`` function (with automatic
  36. calculation of a good default bin size) with the seaborn :func:`kdeplot`
  37. and :func:`rugplot` functions. It can also fit ``scipy.stats``
  38. distributions and plot the estimated PDF over the data.
  39. Parameters
  40. ----------
  41. a : Series, 1d-array, or list.
  42. Observed data. If this is a Series object with a ``name`` attribute,
  43. the name will be used to label the data axis.
  44. bins : argument for matplotlib hist(), or None, optional
  45. Specification of hist bins. If unspecified, as reference rule is used
  46. that tries to find a useful default.
  47. hist : bool, optional
  48. Whether to plot a (normed) histogram.
  49. kde : bool, optional
  50. Whether to plot a gaussian kernel density estimate.
  51. rug : bool, optional
  52. Whether to draw a rugplot on the support axis.
  53. fit : random variable object, optional
  54. An object with `fit` method, returning a tuple that can be passed to a
  55. `pdf` method a positional arguments following a grid of values to
  56. evaluate the pdf on.
  57. hist_kws : dict, optional
  58. Keyword arguments for :meth:`matplotlib.axes.Axes.hist`.
  59. kde_kws : dict, optional
  60. Keyword arguments for :func:`kdeplot`.
  61. rug_kws : dict, optional
  62. Keyword arguments for :func:`rugplot`.
  63. color : matplotlib color, optional
  64. Color to plot everything but the fitted curve in.
  65. vertical : bool, optional
  66. If True, observed values are on y-axis.
  67. norm_hist : bool, optional
  68. If True, the histogram height shows a density rather than a count.
  69. This is implied if a KDE or fitted density is plotted.
  70. axlabel : string, False, or None, optional
  71. Name for the support axis label. If None, will try to get it
  72. from a.name if False, do not set a label.
  73. label : string, optional
  74. Legend label for the relevant component of the plot.
  75. ax : matplotlib axis, optional
  76. If provided, plot on this axis.
  77. Returns
  78. -------
  79. ax : matplotlib Axes
  80. Returns the Axes object with the plot for further tweaking.
  81. See Also
  82. --------
  83. kdeplot : Show a univariate or bivariate distribution with a kernel
  84. density estimate.
  85. rugplot : Draw small vertical lines to show each observation in a
  86. distribution.
  87. Examples
  88. --------
  89. Show a default plot with a kernel density estimate and histogram with bin
  90. size determined automatically with a reference rule:
  91. .. plot::
  92. :context: close-figs
  93. >>> import seaborn as sns, numpy as np
  94. >>> sns.set(); np.random.seed(0)
  95. >>> x = np.random.randn(100)
  96. >>> ax = sns.distplot(x)
  97. Use Pandas objects to get an informative axis label:
  98. .. plot::
  99. :context: close-figs
  100. >>> import pandas as pd
  101. >>> x = pd.Series(x, name="x variable")
  102. >>> ax = sns.distplot(x)
  103. Plot the distribution with a kernel density estimate and rug plot:
  104. .. plot::
  105. :context: close-figs
  106. >>> ax = sns.distplot(x, rug=True, hist=False)
  107. Plot the distribution with a histogram and maximum likelihood gaussian
  108. distribution fit:
  109. .. plot::
  110. :context: close-figs
  111. >>> from scipy.stats import norm
  112. >>> ax = sns.distplot(x, fit=norm, kde=False)
  113. Plot the distribution on the vertical axis:
  114. .. plot::
  115. :context: close-figs
  116. >>> ax = sns.distplot(x, vertical=True)
  117. Change the color of all the plot elements:
  118. .. plot::
  119. :context: close-figs
  120. >>> sns.set_color_codes()
  121. >>> ax = sns.distplot(x, color="y")
  122. Pass specific parameters to the underlying plot functions:
  123. .. plot::
  124. :context: close-figs
  125. >>> ax = sns.distplot(x, rug=True, rug_kws={"color": "g"},
  126. ... kde_kws={"color": "k", "lw": 3, "label": "KDE"},
  127. ... hist_kws={"histtype": "step", "linewidth": 3,
  128. ... "alpha": 1, "color": "g"})
  129. """
  130. if ax is None:
  131. ax = plt.gca()
  132. # Intelligently label the support axis
  133. label_ax = bool(axlabel)
  134. if axlabel is None and hasattr(a, "name"):
  135. axlabel = a.name
  136. if axlabel is not None:
  137. label_ax = True
  138. # Make a a 1-d float array
  139. a = np.asarray(a, np.float)
  140. if a.ndim > 1:
  141. a = a.squeeze()
  142. # Drop null values from array
  143. a = remove_na(a)
  144. # Decide if the hist is normed
  145. norm_hist = norm_hist or kde or (fit is not None)
  146. # Handle dictionary defaults
  147. hist_kws = {} if hist_kws is None else hist_kws.copy()
  148. kde_kws = {} if kde_kws is None else kde_kws.copy()
  149. rug_kws = {} if rug_kws is None else rug_kws.copy()
  150. fit_kws = {} if fit_kws is None else fit_kws.copy()
  151. # Get the color from the current color cycle
  152. if color is None:
  153. if vertical:
  154. line, = ax.plot(0, a.mean())
  155. else:
  156. line, = ax.plot(a.mean(), 0)
  157. color = line.get_color()
  158. line.remove()
  159. # Plug the label into the right kwarg dictionary
  160. if label is not None:
  161. if hist:
  162. hist_kws["label"] = label
  163. elif kde:
  164. kde_kws["label"] = label
  165. elif rug:
  166. rug_kws["label"] = label
  167. elif fit:
  168. fit_kws["label"] = label
  169. if hist:
  170. if bins is None:
  171. bins = min(_freedman_diaconis_bins(a), 50)
  172. hist_kws.setdefault("alpha", 0.4)
  173. hist_kws.setdefault("density", norm_hist)
  174. orientation = "horizontal" if vertical else "vertical"
  175. hist_color = hist_kws.pop("color", color)
  176. ax.hist(a, bins, orientation=orientation,
  177. color=hist_color, **hist_kws)
  178. if hist_color != color:
  179. hist_kws["color"] = hist_color
  180. if kde:
  181. kde_color = kde_kws.pop("color", color)
  182. kdeplot(a, vertical=vertical, ax=ax, color=kde_color, **kde_kws)
  183. if kde_color != color:
  184. kde_kws["color"] = kde_color
  185. if rug:
  186. rug_color = rug_kws.pop("color", color)
  187. axis = "y" if vertical else "x"
  188. rugplot(a, axis=axis, ax=ax, color=rug_color, **rug_kws)
  189. if rug_color != color:
  190. rug_kws["color"] = rug_color
  191. if fit is not None:
  192. def pdf(x):
  193. return fit.pdf(x, *params)
  194. fit_color = fit_kws.pop("color", "#282828")
  195. gridsize = fit_kws.pop("gridsize", 200)
  196. cut = fit_kws.pop("cut", 3)
  197. clip = fit_kws.pop("clip", (-np.inf, np.inf))
  198. bw = stats.gaussian_kde(a).scotts_factor() * a.std(ddof=1)
  199. x = _kde_support(a, bw, gridsize, cut, clip)
  200. params = fit.fit(a)
  201. y = pdf(x)
  202. if vertical:
  203. x, y = y, x
  204. ax.plot(x, y, color=fit_color, **fit_kws)
  205. if fit_color != "#282828":
  206. fit_kws["color"] = fit_color
  207. if label_ax:
  208. if vertical:
  209. ax.set_ylabel(axlabel)
  210. else:
  211. ax.set_xlabel(axlabel)
  212. return ax
  213. def _univariate_kdeplot(data, shade, vertical, kernel, bw, gridsize, cut,
  214. clip, legend, ax, cumulative=False, **kwargs):
  215. """Plot a univariate kernel density estimate on one of the axes."""
  216. # Sort out the clipping
  217. if clip is None:
  218. clip = (-np.inf, np.inf)
  219. # Preprocess the data
  220. data = remove_na(data)
  221. # Calculate the KDE
  222. if np.nan_to_num(data.var()) == 0:
  223. # Don't try to compute KDE on singular data
  224. msg = "Data must have variance to compute a kernel density estimate."
  225. warnings.warn(msg, UserWarning)
  226. x, y = np.array([]), np.array([])
  227. elif _has_statsmodels:
  228. # Prefer using statsmodels for kernel flexibility
  229. x, y = _statsmodels_univariate_kde(data, kernel, bw,
  230. gridsize, cut, clip,
  231. cumulative=cumulative)
  232. else:
  233. # Fall back to scipy if missing statsmodels
  234. if kernel != "gau":
  235. kernel = "gau"
  236. msg = "Kernel other than `gau` requires statsmodels."
  237. warnings.warn(msg, UserWarning)
  238. if cumulative:
  239. raise ImportError("Cumulative distributions are currently "
  240. "only implemented in statsmodels. "
  241. "Please install statsmodels.")
  242. x, y = _scipy_univariate_kde(data, bw, gridsize, cut, clip)
  243. # Make sure the density is nonnegative
  244. y = np.amax(np.c_[np.zeros_like(y), y], axis=1)
  245. # Flip the data if the plot should be on the y axis
  246. if vertical:
  247. x, y = y, x
  248. # Check if a label was specified in the call
  249. label = kwargs.pop("label", None)
  250. # Otherwise check if the data object has a name
  251. if label is None and hasattr(data, "name"):
  252. label = data.name
  253. # Decide if we're going to add a legend
  254. legend = label is not None and legend
  255. label = "_nolegend_" if label is None else label
  256. # Use the active color cycle to find the plot color
  257. facecolor = kwargs.pop("facecolor", None)
  258. line, = ax.plot(x, y, **kwargs)
  259. color = line.get_color()
  260. line.remove()
  261. kwargs.pop("color", None)
  262. facecolor = color if facecolor is None else facecolor
  263. # Draw the KDE plot and, optionally, shade
  264. ax.plot(x, y, color=color, label=label, **kwargs)
  265. shade_kws = dict(
  266. facecolor=facecolor,
  267. alpha=kwargs.get("alpha", 0.25),
  268. clip_on=kwargs.get("clip_on", True),
  269. zorder=kwargs.get("zorder", 1),
  270. )
  271. if shade:
  272. if vertical:
  273. ax.fill_betweenx(y, 0, x, **shade_kws)
  274. else:
  275. ax.fill_between(x, 0, y, **shade_kws)
  276. # Set the density axis minimum to 0
  277. if vertical:
  278. ax.set_xlim(0, auto=None)
  279. else:
  280. ax.set_ylim(0, auto=None)
  281. # Draw the legend here
  282. handles, labels = ax.get_legend_handles_labels()
  283. if legend and handles:
  284. ax.legend(loc="best")
  285. return ax
  286. def _statsmodels_univariate_kde(data, kernel, bw, gridsize, cut, clip,
  287. cumulative=False):
  288. """Compute a univariate kernel density estimate using statsmodels."""
  289. fft = kernel == "gau"
  290. kde = smnp.KDEUnivariate(data)
  291. try:
  292. kde.fit(kernel, bw, fft, gridsize=gridsize, cut=cut, clip=clip)
  293. except RuntimeError as err: # GH#1990
  294. if stats.iqr(data) > 0:
  295. raise err
  296. msg = "Default bandwidth for data is 0; skipping density estimation."
  297. warnings.warn(msg, UserWarning)
  298. return np.array([]), np.array([])
  299. if cumulative:
  300. grid, y = kde.support, kde.cdf
  301. else:
  302. grid, y = kde.support, kde.density
  303. return grid, y
  304. def _scipy_univariate_kde(data, bw, gridsize, cut, clip):
  305. """Compute a univariate kernel density estimate using scipy."""
  306. kde = stats.gaussian_kde(data, bw_method=bw)
  307. if isinstance(bw, str):
  308. bw = "scotts" if bw == "scott" else bw
  309. bw = getattr(kde, "%s_factor" % bw)() * np.std(data)
  310. grid = _kde_support(data, bw, gridsize, cut, clip)
  311. y = kde(grid)
  312. return grid, y
  313. def _bivariate_kdeplot(x, y, filled, fill_lowest,
  314. kernel, bw, gridsize, cut, clip,
  315. axlabel, cbar, cbar_ax, cbar_kws, ax, **kwargs):
  316. """Plot a joint KDE estimate as a bivariate contour plot."""
  317. # Determine the clipping
  318. if clip is None:
  319. clip = [(-np.inf, np.inf), (-np.inf, np.inf)]
  320. elif np.ndim(clip) == 1:
  321. clip = [clip, clip]
  322. # Calculate the KDE
  323. if _has_statsmodels:
  324. xx, yy, z = _statsmodels_bivariate_kde(x, y, bw, gridsize, cut, clip)
  325. else:
  326. xx, yy, z = _scipy_bivariate_kde(x, y, bw, gridsize, cut, clip)
  327. # Plot the contours
  328. n_levels = kwargs.pop("n_levels", 10)
  329. scout, = ax.plot([], [])
  330. default_color = scout.get_color()
  331. scout.remove()
  332. cmap = kwargs.pop("cmap", None)
  333. color = kwargs.pop("color", None)
  334. if cmap is None and "colors" not in kwargs:
  335. if color is None:
  336. color = default_color
  337. if filled:
  338. cmap = light_palette(color, as_cmap=True)
  339. else:
  340. cmap = dark_palette(color, as_cmap=True)
  341. if isinstance(cmap, str):
  342. if cmap.endswith("_d"):
  343. pal = ["#333333"]
  344. pal.extend(color_palette(cmap.replace("_d", "_r"), 2))
  345. cmap = blend_palette(pal, as_cmap=True)
  346. else:
  347. cmap = mpl.cm.get_cmap(cmap)
  348. label = kwargs.pop("label", None)
  349. kwargs["cmap"] = cmap
  350. contour_func = ax.contourf if filled else ax.contour
  351. cset = contour_func(xx, yy, z, n_levels, **kwargs)
  352. if filled and not fill_lowest:
  353. cset.collections[0].set_alpha(0)
  354. kwargs["n_levels"] = n_levels
  355. if cbar:
  356. cbar_kws = {} if cbar_kws is None else cbar_kws
  357. ax.figure.colorbar(cset, cbar_ax, ax, **cbar_kws)
  358. # Label the axes
  359. if hasattr(x, "name") and axlabel:
  360. ax.set_xlabel(x.name)
  361. if hasattr(y, "name") and axlabel:
  362. ax.set_ylabel(y.name)
  363. if label is not None:
  364. legend_color = cmap(.95) if color is None else color
  365. if filled:
  366. ax.fill_between([], [], color=legend_color, label=label)
  367. else:
  368. ax.plot([], [], color=legend_color, label=label)
  369. return ax
  370. def _statsmodels_bivariate_kde(x, y, bw, gridsize, cut, clip):
  371. """Compute a bivariate kde using statsmodels."""
  372. if isinstance(bw, str):
  373. bw_func = getattr(smnp.bandwidths, "bw_" + bw)
  374. x_bw = bw_func(x)
  375. y_bw = bw_func(y)
  376. bw = [x_bw, y_bw]
  377. elif np.isscalar(bw):
  378. bw = [bw, bw]
  379. if isinstance(x, pd.Series):
  380. x = x.values
  381. if isinstance(y, pd.Series):
  382. y = y.values
  383. kde = smnp.KDEMultivariate([x, y], "cc", bw)
  384. x_support = _kde_support(x, kde.bw[0], gridsize, cut, clip[0])
  385. y_support = _kde_support(y, kde.bw[1], gridsize, cut, clip[1])
  386. xx, yy = np.meshgrid(x_support, y_support)
  387. z = kde.pdf([xx.ravel(), yy.ravel()]).reshape(xx.shape)
  388. return xx, yy, z
  389. def _scipy_bivariate_kde(x, y, bw, gridsize, cut, clip):
  390. """Compute a bivariate kde using scipy."""
  391. data = np.c_[x, y]
  392. kde = stats.gaussian_kde(data.T, bw_method=bw)
  393. data_std = data.std(axis=0, ddof=1)
  394. if isinstance(bw, str):
  395. bw = "scotts" if bw == "scott" else bw
  396. bw_x = getattr(kde, "%s_factor" % bw)() * data_std[0]
  397. bw_y = getattr(kde, "%s_factor" % bw)() * data_std[1]
  398. elif np.isscalar(bw):
  399. bw_x, bw_y = bw, bw
  400. else:
  401. msg = ("Cannot specify a different bandwidth for each dimension "
  402. "with the scipy backend. You should install statsmodels.")
  403. raise ValueError(msg)
  404. x_support = _kde_support(data[:, 0], bw_x, gridsize, cut, clip[0])
  405. y_support = _kde_support(data[:, 1], bw_y, gridsize, cut, clip[1])
  406. xx, yy = np.meshgrid(x_support, y_support)
  407. z = kde([xx.ravel(), yy.ravel()]).reshape(xx.shape)
  408. return xx, yy, z
  409. def kdeplot(data, data2=None, shade=False, vertical=False, kernel="gau",
  410. bw="scott", gridsize=100, cut=3, clip=None, legend=True,
  411. cumulative=False, shade_lowest=True, cbar=False, cbar_ax=None,
  412. cbar_kws=None, ax=None, **kwargs):
  413. """Fit and plot a univariate or bivariate kernel density estimate.
  414. Parameters
  415. ----------
  416. data : 1d array-like
  417. Input data.
  418. data2: 1d array-like, optional
  419. Second input data. If present, a bivariate KDE will be estimated.
  420. shade : bool, optional
  421. If True, shade in the area under the KDE curve (or draw with filled
  422. contours when data is bivariate).
  423. vertical : bool, optional
  424. If True, density is on x-axis.
  425. kernel : {'gau' | 'cos' | 'biw' | 'epa' | 'tri' | 'triw' }, optional
  426. Code for shape of kernel to fit with. Bivariate KDE can only use
  427. gaussian kernel.
  428. bw : {'scott' | 'silverman' | scalar | pair of scalars }, optional
  429. Name of reference method to determine kernel size, scalar factor,
  430. or scalar for each dimension of the bivariate plot. Note that the
  431. underlying computational libraries have different interperetations
  432. for this parameter: ``statsmodels`` uses it directly, but ``scipy``
  433. treats it as a scaling factor for the standard deviation of the
  434. data.
  435. gridsize : int, optional
  436. Number of discrete points in the evaluation grid.
  437. cut : scalar, optional
  438. Draw the estimate to cut * bw from the extreme data points.
  439. clip : pair of scalars, or pair of pair of scalars, optional
  440. Lower and upper bounds for datapoints used to fit KDE. Can provide
  441. a pair of (low, high) bounds for bivariate plots.
  442. legend : bool, optional
  443. If True, add a legend or label the axes when possible.
  444. cumulative : bool, optional
  445. If True, draw the cumulative distribution estimated by the kde.
  446. shade_lowest : bool, optional
  447. If True, shade the lowest contour of a bivariate KDE plot. Not
  448. relevant when drawing a univariate plot or when ``shade=False``.
  449. Setting this to ``False`` can be useful when you want multiple
  450. densities on the same Axes.
  451. cbar : bool, optional
  452. If True and drawing a bivariate KDE plot, add a colorbar.
  453. cbar_ax : matplotlib axes, optional
  454. Existing axes to draw the colorbar onto, otherwise space is taken
  455. from the main axes.
  456. cbar_kws : dict, optional
  457. Keyword arguments for ``fig.colorbar()``.
  458. ax : matplotlib axes, optional
  459. Axes to plot on, otherwise uses current axes.
  460. kwargs : key, value pairings
  461. Other keyword arguments are passed to ``plt.plot()`` or
  462. ``plt.contour{f}`` depending on whether a univariate or bivariate
  463. plot is being drawn.
  464. Returns
  465. -------
  466. ax : matplotlib Axes
  467. Axes with plot.
  468. See Also
  469. --------
  470. distplot: Flexibly plot a univariate distribution of observations.
  471. jointplot: Plot a joint dataset with bivariate and marginal distributions.
  472. Examples
  473. --------
  474. Plot a basic univariate density:
  475. .. plot::
  476. :context: close-figs
  477. >>> import numpy as np; np.random.seed(10)
  478. >>> import seaborn as sns; sns.set(color_codes=True)
  479. >>> mean, cov = [0, 2], [(1, .5), (.5, 1)]
  480. >>> x, y = np.random.multivariate_normal(mean, cov, size=50).T
  481. >>> ax = sns.kdeplot(x)
  482. Shade under the density curve and use a different color:
  483. .. plot::
  484. :context: close-figs
  485. >>> ax = sns.kdeplot(x, shade=True, color="r")
  486. Plot a bivariate density:
  487. .. plot::
  488. :context: close-figs
  489. >>> ax = sns.kdeplot(x, y)
  490. Use filled contours:
  491. .. plot::
  492. :context: close-figs
  493. >>> ax = sns.kdeplot(x, y, shade=True)
  494. Use more contour levels and a different color palette:
  495. .. plot::
  496. :context: close-figs
  497. >>> ax = sns.kdeplot(x, y, n_levels=30, cmap="Purples_d")
  498. Use a narrower bandwith:
  499. .. plot::
  500. :context: close-figs
  501. >>> ax = sns.kdeplot(x, bw=.15)
  502. Plot the density on the vertical axis:
  503. .. plot::
  504. :context: close-figs
  505. >>> ax = sns.kdeplot(y, vertical=True)
  506. Limit the density curve within the range of the data:
  507. .. plot::
  508. :context: close-figs
  509. >>> ax = sns.kdeplot(x, cut=0)
  510. Add a colorbar for the contours:
  511. .. plot::
  512. :context: close-figs
  513. >>> ax = sns.kdeplot(x, y, cbar=True)
  514. Plot two shaded bivariate densities:
  515. .. plot::
  516. :context: close-figs
  517. >>> iris = sns.load_dataset("iris")
  518. >>> setosa = iris.loc[iris.species == "setosa"]
  519. >>> virginica = iris.loc[iris.species == "virginica"]
  520. >>> ax = sns.kdeplot(setosa.sepal_width, setosa.sepal_length,
  521. ... cmap="Reds", shade=True, shade_lowest=False)
  522. >>> ax = sns.kdeplot(virginica.sepal_width, virginica.sepal_length,
  523. ... cmap="Blues", shade=True, shade_lowest=False)
  524. """
  525. if ax is None:
  526. ax = plt.gca()
  527. if isinstance(data, list):
  528. data = np.asarray(data)
  529. if len(data) == 0:
  530. return ax
  531. data = data.astype(np.float64)
  532. if data2 is not None:
  533. if isinstance(data2, list):
  534. data2 = np.asarray(data2)
  535. data2 = data2.astype(np.float64)
  536. warn = False
  537. bivariate = False
  538. if isinstance(data, np.ndarray) and np.ndim(data) > 1:
  539. warn = True
  540. bivariate = True
  541. x, y = data.T
  542. elif isinstance(data, pd.DataFrame) and np.ndim(data) > 1:
  543. warn = True
  544. bivariate = True
  545. x = data.iloc[:, 0].values
  546. y = data.iloc[:, 1].values
  547. elif data2 is not None:
  548. bivariate = True
  549. x = data
  550. y = data2
  551. if warn:
  552. warn_msg = ("Passing a 2D dataset for a bivariate plot is deprecated "
  553. "in favor of kdeplot(x, y), and it will cause an error in "
  554. "future versions. Please update your code.")
  555. warnings.warn(warn_msg, UserWarning)
  556. if bivariate and cumulative:
  557. raise TypeError("Cumulative distribution plots are not"
  558. "supported for bivariate distributions.")
  559. if bivariate:
  560. ax = _bivariate_kdeplot(x, y, shade, shade_lowest,
  561. kernel, bw, gridsize, cut, clip, legend,
  562. cbar, cbar_ax, cbar_kws, ax, **kwargs)
  563. else:
  564. ax = _univariate_kdeplot(data, shade, vertical, kernel, bw,
  565. gridsize, cut, clip, legend, ax,
  566. cumulative=cumulative, **kwargs)
  567. return ax
  568. def rugplot(a, height=.05, axis="x", ax=None, **kwargs):
  569. """Plot datapoints in an array as sticks on an axis.
  570. Parameters
  571. ----------
  572. a : vector
  573. 1D array of observations.
  574. height : scalar, optional
  575. Height of ticks as proportion of the axis.
  576. axis : {'x' | 'y'}, optional
  577. Axis to draw rugplot on.
  578. ax : matplotlib axes, optional
  579. Axes to draw plot into; otherwise grabs current axes.
  580. kwargs : key, value pairings
  581. Other keyword arguments are passed to ``LineCollection``.
  582. Returns
  583. -------
  584. ax : matplotlib axes
  585. The Axes object with the plot on it.
  586. """
  587. if ax is None:
  588. ax = plt.gca()
  589. a = np.asarray(a)
  590. vertical = kwargs.pop("vertical", axis == "y")
  591. alias_map = dict(linewidth="lw", linestyle="ls", color="c")
  592. for attr, alias in alias_map.items():
  593. if alias in kwargs:
  594. kwargs[attr] = kwargs.pop(alias)
  595. kwargs.setdefault("linewidth", 1)
  596. if vertical:
  597. trans = tx.blended_transform_factory(ax.transAxes, ax.transData)
  598. xy_pairs = np.column_stack([np.tile([0, height], len(a)),
  599. np.repeat(a, 2)])
  600. else:
  601. trans = tx.blended_transform_factory(ax.transData, ax.transAxes)
  602. xy_pairs = np.column_stack([np.repeat(a, 2),
  603. np.tile([0, height], len(a))])
  604. line_segs = xy_pairs.reshape([len(a), 2, 2])
  605. ax.add_collection(LineCollection(line_segs, transform=trans, **kwargs))
  606. ax.autoscale_view(scalex=not vertical, scaley=vertical)
  607. return ax