{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Box plot vs. violin plot comparison\n\nNote that although violin plots are closely related to Tukey's (1977)\nbox plots, they add useful information such as the distribution of the\nsample data (density trace).\n\nBy default, box plots show data points outside 1.5 * the inter-quartile\nrange as outliers above or below the whiskers whereas violin plots show\nthe whole range of the data.\n\nA good general reference on boxplots and their history can be found\nhere: http://vita.had.co.nz/papers/boxplots.pdf\n\nViolin plots require matplotlib >= 1.4.\n\nFor more information on violin plots, the scikit-learn docs have a great\nsection: https://scikit-learn.org/stable/modules/density.html\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nfig, axs = plt.subplots(nrows=1, ncols=2, figsize=(9, 4))\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\n# generate some random test data\nall_data = [np.random.normal(0, std, 100) for std in range(6, 10)]\n\n# plot violin plot\naxs[0].violinplot(all_data,\n showmeans=False,\n showmedians=True)\naxs[0].set_title('Violin plot')\n\n# plot box plot\naxs[1].boxplot(all_data)\naxs[1].set_title('Box plot')\n\n# adding horizontal grid lines\nfor ax in axs:\n ax.yaxis.grid(True)\n ax.set_xticks([y + 1 for y in range(len(all_data))],\n labels=['x1', 'x2', 'x3', 'x4'])\n ax.set_xlabel('Four separate samples')\n ax.set_ylabel('Observed values')\n\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. tags:: plot-type: violin, plot-type: boxplot, domain: statistics\n\n.. admonition:: References\n\n The use of the following functions, methods, classes and modules is shown\n in this example:\n\n - `matplotlib.axes.Axes.boxplot` / `matplotlib.pyplot.boxplot`\n - `matplotlib.axes.Axes.violinplot` / `matplotlib.pyplot.violinplot`\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }