{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Style sheets reference\n\nThis script demonstrates the different available style sheets on a\ncommon set of example plots: scatter plot, image, bar graph, patches,\nline plot and histogram.\n\nAny of these style sheets can be imported (i.e. activated) by its name.\nFor example for the ggplot style:\n\n>>> plt.style.use('ggplot')\n\nThe names of the available style sheets can be found\nin the list `matplotlib.style.available`\n(they are also printed in the corner of each plot below).\n\nSee more details in `Customizing Matplotlib\nusing style sheets`.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib.colors as mcolors\nfrom matplotlib.patches import Rectangle\n\n# Fixing random state for reproducibility\nnp.random.seed(19680801)\n\n\ndef plot_scatter(ax, prng, nb_samples=100):\n \"\"\"Scatter plot.\"\"\"\n for mu, sigma, marker in [(-.5, 0.75, 'o'), (0.75, 1., 's')]:\n x, y = prng.normal(loc=mu, scale=sigma, size=(2, nb_samples))\n ax.plot(x, y, ls='none', marker=marker)\n ax.set_xlabel('X-label')\n ax.set_title('Axes title')\n return ax\n\n\ndef plot_colored_lines(ax):\n \"\"\"Plot lines with colors following the style color cycle.\"\"\"\n t = np.linspace(-10, 10, 100)\n\n def sigmoid(t, t0):\n return 1 / (1 + np.exp(-(t - t0)))\n\n nb_colors = len(plt.rcParams['axes.prop_cycle'])\n shifts = np.linspace(-5, 5, nb_colors)\n amplitudes = np.linspace(1, 1.5, nb_colors)\n for t0, a in zip(shifts, amplitudes):\n ax.plot(t, a * sigmoid(t, t0), '-')\n ax.set_xlim(-10, 10)\n return ax\n\n\ndef plot_bar_graphs(ax, prng, min_value=5, max_value=25, nb_samples=5):\n \"\"\"Plot two bar graphs side by side, with letters as x-tick labels.\"\"\"\n x = np.arange(nb_samples)\n ya, yb = prng.randint(min_value, max_value, size=(2, nb_samples))\n width = 0.25\n ax.bar(x, ya, width)\n ax.bar(x + width, yb, width, color='C2')\n ax.set_xticks(x + width, labels=['a', 'b', 'c', 'd', 'e'])\n return ax\n\n\ndef plot_colored_circles(ax, prng, nb_samples=15):\n \"\"\"\n Plot circle patches.\n\n NB: draws a fixed amount of samples, rather than using the length of\n the color cycle, because different styles may have different numbers\n of colors.\n \"\"\"\n for sty_dict, j in zip(plt.rcParams['axes.prop_cycle'](),\n range(nb_samples)):\n ax.add_patch(plt.Circle(prng.normal(scale=3, size=2),\n radius=1.0, color=sty_dict['color']))\n ax.grid(visible=True)\n\n # Add title for enabling grid\n plt.title('ax.grid(True)', family='monospace', fontsize='small')\n\n ax.set_xlim([-4, 8])\n ax.set_ylim([-5, 6])\n ax.set_aspect('equal', adjustable='box') # to plot circles as circles\n return ax\n\n\ndef plot_image_and_patch(ax, prng, size=(20, 20)):\n \"\"\"Plot an image with random values and superimpose a circular patch.\"\"\"\n values = prng.random_sample(size=size)\n ax.imshow(values, interpolation='none')\n c = plt.Circle((5, 5), radius=5, label='patch')\n ax.add_patch(c)\n # Remove ticks\n ax.set_xticks([])\n ax.set_yticks([])\n\n\ndef plot_histograms(ax, prng, nb_samples=10000):\n \"\"\"Plot 4 histograms and a text annotation.\"\"\"\n params = ((10, 10), (4, 12), (50, 12), (6, 55))\n for a, b in params:\n values = prng.beta(a, b, size=nb_samples)\n ax.hist(values, histtype=\"stepfilled\", bins=30,\n alpha=0.8, density=True)\n\n # Add a small annotation.\n ax.annotate('Annotation', xy=(0.25, 4.25),\n xytext=(0.9, 0.9), textcoords=ax.transAxes,\n va=\"top\", ha=\"right\",\n bbox=dict(boxstyle=\"round\", alpha=0.2),\n arrowprops=dict(\n arrowstyle=\"->\",\n connectionstyle=\"angle,angleA=-95,angleB=35,rad=10\"),\n )\n return ax\n\n\ndef plot_figure(style_label=\"\"):\n \"\"\"Setup and plot the demonstration figure with a given style.\"\"\"\n # Use a dedicated RandomState instance to draw the same \"random\" values\n # across the different figures.\n prng = np.random.RandomState(96917002)\n\n fig, axs = plt.subplots(ncols=6, nrows=1, num=style_label,\n figsize=(14.8, 2.8), layout='constrained')\n\n # make a suptitle, in the same style for all subfigures,\n # except those with dark backgrounds, which get a lighter color:\n background_color = mcolors.rgb_to_hsv(\n mcolors.to_rgb(plt.rcParams['figure.facecolor']))[2]\n if background_color < 0.5:\n title_color = [0.8, 0.8, 1]\n else:\n title_color = np.array([19, 6, 84]) / 256\n fig.suptitle(style_label, x=0.01, ha='left', color=title_color,\n fontsize=14, fontfamily='DejaVu Sans', fontweight='normal')\n\n plot_scatter(axs[0], prng)\n plot_image_and_patch(axs[1], prng)\n plot_bar_graphs(axs[2], prng)\n plot_colored_lines(axs[3])\n plot_histograms(axs[4], prng)\n plot_colored_circles(axs[5], prng)\n\n # add divider\n rec = Rectangle((1 + 0.025, -2), 0.05, 16,\n clip_on=False, color='gray')\n\n axs[4].add_artist(rec)\n\nif __name__ == \"__main__\":\n\n # Set up a list of all available styles, in alphabetical order but\n # the `default` and `classic` ones, which will be forced resp. in\n # first and second position.\n # styles with leading underscores are for internal use such as testing\n # and plot types gallery. These are excluded here.\n style_list = ['default', 'classic'] + sorted(\n style for style in plt.style.available\n if style != 'classic' and not style.startswith('_'))\n\n # Plot a demonstration figure for every available style sheet.\n for style_label in style_list:\n with plt.rc_context({\"figure.max_open_warning\": len(style_list)}):\n with plt.style.context(style_label):\n plot_figure(style_label=style_label)\n\n plt.show()" ] } ], "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 }