{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Radar chart (aka spider or star chart)\n\nThis example creates a radar chart, also known as a spider or star chart [1]_.\n\nAlthough this example allows a frame of either 'circle' or 'polygon', polygon\nframes don't have proper gridlines (the lines are circles instead of polygons).\nIt's possible to get a polygon grid by setting GRIDLINE_INTERPOLATION_STEPS in\n`matplotlib.axis` to the desired number of vertices, but the orientation of the\npolygon is not aligned with the radial axis.\n\n.. [1] https://en.wikipedia.org/wiki/Radar_chart\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.patches import Circle, RegularPolygon\nfrom matplotlib.path import Path\nfrom matplotlib.projections import register_projection\nfrom matplotlib.projections.polar import PolarAxes\nfrom matplotlib.spines import Spine\nfrom matplotlib.transforms import Affine2D\n\n\ndef radar_factory(num_vars, frame='circle'):\n \"\"\"\n Create a radar chart with `num_vars` Axes.\n\n This function creates a RadarAxes projection and registers it.\n\n Parameters\n ----------\n num_vars : int\n Number of variables for radar chart.\n frame : {'circle', 'polygon'}\n Shape of frame surrounding Axes.\n\n \"\"\"\n # calculate evenly-spaced axis angles\n theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)\n\n class RadarTransform(PolarAxes.PolarTransform):\n\n def transform_path_non_affine(self, path):\n # Paths with non-unit interpolation steps correspond to gridlines,\n # in which case we force interpolation (to defeat PolarTransform's\n # autoconversion to circular arcs).\n if path._interpolation_steps > 1:\n path = path.interpolated(num_vars)\n return Path(self.transform(path.vertices), path.codes)\n\n class RadarAxes(PolarAxes):\n\n name = 'radar'\n PolarTransform = RadarTransform\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # rotate plot such that the first axis is at the top\n self.set_theta_zero_location('N')\n\n def fill(self, *args, closed=True, **kwargs):\n \"\"\"Override fill so that line is closed by default\"\"\"\n return super().fill(closed=closed, *args, **kwargs)\n\n def plot(self, *args, **kwargs):\n \"\"\"Override plot so that line is closed by default\"\"\"\n lines = super().plot(*args, **kwargs)\n for line in lines:\n self._close_line(line)\n\n def _close_line(self, line):\n x, y = line.get_data()\n # FIXME: markers at x[0], y[0] get doubled-up\n if x[0] != x[-1]:\n x = np.append(x, x[0])\n y = np.append(y, y[0])\n line.set_data(x, y)\n\n def set_varlabels(self, labels):\n self.set_thetagrids(np.degrees(theta), labels)\n\n def _gen_axes_patch(self):\n # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5\n # in axes coordinates.\n if frame == 'circle':\n return Circle((0.5, 0.5), 0.5)\n elif frame == 'polygon':\n return RegularPolygon((0.5, 0.5), num_vars,\n radius=.5, edgecolor=\"k\")\n else:\n raise ValueError(\"Unknown value for 'frame': %s\" % frame)\n\n def _gen_axes_spines(self):\n if frame == 'circle':\n return super()._gen_axes_spines()\n elif frame == 'polygon':\n # spine_type must be 'left'/'right'/'top'/'bottom'/'circle'.\n spine = Spine(axes=self,\n spine_type='circle',\n path=Path.unit_regular_polygon(num_vars))\n # unit_regular_polygon gives a polygon of radius 1 centered at\n # (0, 0) but we want a polygon of radius 0.5 centered at (0.5,\n # 0.5) in axes coordinates.\n spine.set_transform(Affine2D().scale(.5).translate(.5, .5)\n + self.transAxes)\n return {'polar': spine}\n else:\n raise ValueError(\"Unknown value for 'frame': %s\" % frame)\n\n register_projection(RadarAxes)\n return theta\n\n\ndef example_data():\n # The following data is from the Denver Aerosol Sources and Health study.\n # See doi:10.1016/j.atmosenv.2008.12.017\n #\n # The data are pollution source profile estimates for five modeled\n # pollution sources (e.g., cars, wood-burning, etc) that emit 7-9 chemical\n # species. The radar charts are experimented with here to see if we can\n # nicely visualize how the modeled source profiles change across four\n # scenarios:\n # 1) No gas-phase species present, just seven particulate counts on\n # Sulfate\n # Nitrate\n # Elemental Carbon (EC)\n # Organic Carbon fraction 1 (OC)\n # Organic Carbon fraction 2 (OC2)\n # Organic Carbon fraction 3 (OC3)\n # Pyrolyzed Organic Carbon (OP)\n # 2)Inclusion of gas-phase specie carbon monoxide (CO)\n # 3)Inclusion of gas-phase specie ozone (O3).\n # 4)Inclusion of both gas-phase species is present...\n data = [\n ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', 'O3'],\n ('Basecase', [\n [0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00],\n [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00],\n [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00],\n [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00],\n [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]]),\n ('With CO', [\n [0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00],\n [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00],\n [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00],\n [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00],\n [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]]),\n ('With O3', [\n [0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03],\n [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00],\n [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00],\n [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95],\n [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]]),\n ('CO & O3', [\n [0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01],\n [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00],\n [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00],\n [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88],\n [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]])\n ]\n return data\n\n\nif __name__ == '__main__':\n N = 9\n theta = radar_factory(N, frame='polygon')\n\n data = example_data()\n spoke_labels = data.pop(0)\n\n fig, axs = plt.subplots(figsize=(9, 9), nrows=2, ncols=2,\n subplot_kw=dict(projection='radar'))\n fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)\n\n colors = ['b', 'r', 'g', 'm', 'y']\n # Plot the four cases from the example data on separate Axes\n for ax, (title, case_data) in zip(axs.flat, data):\n ax.set_rgrids([0.2, 0.4, 0.6, 0.8])\n ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),\n horizontalalignment='center', verticalalignment='center')\n for d, color in zip(case_data, colors):\n ax.plot(theta, d, color=color)\n ax.fill(theta, d, facecolor=color, alpha=0.25, label='_nolegend_')\n ax.set_varlabels(spoke_labels)\n\n # add legend relative to top-left plot\n labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')\n legend = axs[0, 0].legend(labels, loc=(0.9, .95),\n labelspacing=0.1, fontsize='small')\n\n fig.text(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',\n horizontalalignment='center', color='black', weight='bold',\n size='large')\n\n plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. admonition:: References\n\n The use of the following functions, methods, classes and modules is shown\n in this example:\n\n - `matplotlib.path`\n - `matplotlib.path.Path`\n - `matplotlib.spines`\n - `matplotlib.spines.Spine`\n - `matplotlib.projections`\n - `matplotlib.projections.polar`\n - `matplotlib.projections.polar.PolarAxes`\n - `matplotlib.projections.register_projection`\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 }