{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n.. redirect-from:: /users/customizing\n.. redirect-from:: /tutorials/introductory/customizing\n\n\n# Customizing Matplotlib with style sheets and rcParams\n\nTips for customizing the properties and default styles of Matplotlib.\n\nThere are three ways to customize Matplotlib:\n\n1. `Setting rcParams at runtime`.\n2. `Using style sheets`.\n3. `Changing your matplotlibrc file`.\n\nSetting rcParams at runtime takes precedence over style sheets, style\nsheets take precedence over :file:`matplotlibrc` files.\n\n\n## Runtime rc settings\n\nYou can dynamically change the default rc (runtime configuration)\nsettings in a python script or interactively from the python shell. All\nrc settings are stored in a dictionary-like variable called\n:data:`matplotlib.rcParams`, which is global to the matplotlib package.\nSee `matplotlib.rcParams` for a full list of configurable rcParams.\nrcParams can be modified directly, for example:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from cycler import cycler\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport matplotlib as mpl\n\nmpl.rcParams['lines.linewidth'] = 2\nmpl.rcParams['lines.linestyle'] = '--'\ndata = np.random.randn(50)\nplt.plot(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note, that in order to change the usual `~.Axes.plot` color you have to\nchange the *prop_cycle* property of *axes*:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "mpl.rcParams['axes.prop_cycle'] = cycler(color=['r', 'g', 'b', 'y'])\nplt.plot(data) # first color is red" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Matplotlib also provides a couple of convenience functions for modifying rc\nsettings. `matplotlib.rc` can be used to modify multiple\nsettings in a single group at once, using keyword arguments:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "mpl.rc('lines', linewidth=4, linestyle='-.')\nplt.plot(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Temporary rc settings\n\nThe :data:`matplotlib.rcParams` object can also be changed temporarily using\nthe `matplotlib.rc_context` context manager:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "with mpl.rc_context({'lines.linewidth': 2, 'lines.linestyle': ':'}):\n plt.plot(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`matplotlib.rc_context` can also be used as a decorator to modify the\ndefaults within a function:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "@mpl.rc_context({'lines.linewidth': 3, 'lines.linestyle': '-'})\ndef plotting_function():\n plt.plot(data)\n\nplotting_function()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`matplotlib.rcdefaults` will restore the standard Matplotlib\ndefault settings.\n\nThere is some degree of validation when setting the values of rcParams, see\n:mod:`matplotlib.rcsetup` for details.\n\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n## Using style sheets\n\nAnother way to change the visual appearance of plots is to set the\nrcParams in a so-called style sheet and import that style sheet with\n`matplotlib.style.use`. In this way you can switch easily between\ndifferent styles by simply changing the imported style sheet. A style\nsheets looks the same as a `matplotlibrc`\nfile, but in a style sheet you can only set rcParams that are related\nto the actual style of a plot. Other rcParams, like *backend*, will be\nignored. :file:`matplotlibrc` files support all rcParams. The\nrationale behind this is to make style sheets portable between\ndifferent machines without having to worry about dependencies which\nmight or might not be installed on another machine. For a full list of\nrcParams see `matplotlib.rcParams`. For a list of rcParams that are\nignored in style sheets see `matplotlib.style.use`.\n\nThere are a number of pre-defined styles :doc:`provided by Matplotlib\n`. For\nexample, there's a pre-defined style called \"ggplot\", which emulates the\naesthetics of ggplot_ (a popular plotting package for R_). To use this\nstyle, add:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "plt.style.use('ggplot')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To list all available styles, use:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(plt.style.available)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Defining your own style\n\nYou can create custom styles and use them by calling `.style.use` with\nthe path or URL to the style sheet.\n\nFor example, you might want to create\n``./images/presentation.mplstyle`` with the following::\n\n axes.titlesize : 24\n axes.labelsize : 20\n lines.linewidth : 3\n lines.markersize : 10\n xtick.labelsize : 16\n ytick.labelsize : 16\n\nThen, when you want to adapt a plot designed for a paper to one that looks\ngood in a presentation, you can just add::\n\n >>> import matplotlib.pyplot as plt\n >>> plt.style.use('./images/presentation.mplstyle')\n\n\n### Distributing styles\n\nYou can include style sheets into standard importable Python packages (which\ncan be e.g. distributed on PyPI). If your package is importable as\n``import mypackage``, with a ``mypackage/__init__.py`` module, and you add\na ``mypackage/presentation.mplstyle`` style sheet, then it can be used as\n``plt.style.use(\"mypackage.presentation\")``. Subpackages (e.g.\n``dotted.package.name``) are also supported.\n\nAlternatively, you can make your style known to Matplotlib by placing\nyour ``.mplstyle`` file into ``mpl_configdir/stylelib``. You\ncan then load your custom style sheet with a call to\n``style.use()``. By default ``mpl_configdir`` should be\n``~/.config/matplotlib``, but you can check where yours is with\n`matplotlib.get_configdir()`; you may need to create this directory. You\nalso can change the directory where Matplotlib looks for the stylelib/\nfolder by setting the :envvar:`MPLCONFIGDIR` environment variable, see\n`locating-matplotlib-config-dir`.\n\nNote that a custom style sheet in ``mpl_configdir/stylelib`` will override a\nstyle sheet defined by Matplotlib if the styles have the same name.\n\nOnce your ``.mplstyle`` file is in the appropriate\n``mpl_configdir`` you can specify your style with::\n\n >>> import matplotlib.pyplot as plt\n >>> plt.style.use()\n\n\n### Composing styles\n\nStyle sheets are designed to be composed together. So you can have a style\nsheet that customizes colors and a separate style sheet that alters element\nsizes for presentations. These styles can easily be combined by passing\na list of styles::\n\n >>> import matplotlib.pyplot as plt\n >>> plt.style.use(['dark_background', 'presentation'])\n\nNote that styles further to the right will overwrite values that are already\ndefined by styles on the left.\n\n\n### Temporary styling\n\nIf you only want to use a style for a specific block of code but don't want\nto change the global styling, the style package provides a context manager\nfor limiting your changes to a specific scope. To isolate your styling\nchanges, you can write something like the following:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "with plt.style.context('dark_background'):\n plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n## The :file:`matplotlibrc` file\n\nMatplotlib uses :file:`matplotlibrc` configuration files to customize all\nkinds of properties, which we call 'rc settings' or 'rc parameters'. You can\ncontrol the defaults of almost every property in Matplotlib: figure size and\nDPI, line width, color and style, Axes, axis and grid properties, text and\nfont properties and so on. The :file:`matplotlibrc` is read at startup to\nconfigure Matplotlib. Matplotlib looks for :file:`matplotlibrc` in four\nlocations, in the following order:\n\n1. :file:`matplotlibrc` in the current working directory, usually used for\n specific customizations that you do not want to apply elsewhere.\n\n2. :file:`$MATPLOTLIBRC` if it is a file, else\n :file:`$MATPLOTLIBRC/matplotlibrc`.\n\n3. It next looks in a user-specific place, depending on your platform:\n\n - On Linux and FreeBSD, it looks in\n :file:`.config/matplotlib/matplotlibrc` (or\n :file:`$XDG_CONFIG_HOME/matplotlib/matplotlibrc`) if you've customized\n your environment.\n\n - On other platforms, it looks in :file:`.matplotlib/matplotlibrc`.\n\n See `locating-matplotlib-config-dir`.\n\n4. :file:`{INSTALL}/matplotlib/mpl-data/matplotlibrc`, where\n :file:`{INSTALL}` is something like\n :file:`/usr/lib/python3.10/site-packages` on Linux, and maybe\n :file:`C:\\\\Python310\\\\Lib\\\\site-packages` on Windows. Every time you\n install matplotlib, this file will be overwritten, so if you want\n your customizations to be saved, please move this file to your\n user-specific matplotlib directory.\n\nOnce a :file:`matplotlibrc` file has been found, it will *not* search\nany of the other paths. When a\n`style sheet` is given with\n``style.use('/.mplstyle')``, settings specified in\nthe style sheet take precedence over settings in the\n:file:`matplotlibrc` file.\n\nTo display where the currently active :file:`matplotlibrc` file was\nloaded from, one can do the following::\n\n >>> import matplotlib\n >>> matplotlib.matplotlib_fname()\n '/home/foo/.config/matplotlib/matplotlibrc'\n\nSee below for a sample `matplotlibrc file`\nand see `matplotlib.rcParams` for a full list of configurable rcParams.\n\n\n### The default :file:`matplotlibrc` file\n\n.. literalinclude:: ../../../lib/matplotlib/mpl-data/matplotlibrc\n\n\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 }