"> If you want more advanced distribution plots beyond a simple histogram, have a look at the seaborn [gallery](https://seaborn.pydata.org/examples/index.html) for (too?) many options.\n",
"\n",
"### Adding error bars\n",
"If your data is not completely perfect and has for some obscure reason some uncertainty associated with it, \n",
"plt.text(0.5, 0.5, 'middle of the plot', transform=plt.gca().transAxes, ha='center', va='center')\n",
"plt.annotate(\"line crossing\", (1, -1), (0.8, -0.8), arrowprops={}) # adds both text and arrow; need to set the arrowprops keyword for the arrow to be plotted"
]
},
{
"cell_type": "markdown",
"id": "62d70058",
"metadata": {},
"source": [
"By default the locations of the arrows and text will be in data coordinates (i.e., whatever is on the axes),\n",
"however you can change that. For example to find the middle of the plot in the last example we use\n",
"axes coordinates, which are always (0, 0) in the lower left and (1, 1) in the upper right.\n",
"See the matplotlib [transformations tutorial](https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial.html)\n",
"for more detail.\n",
"\n",
"## Using the object-oriented interface\n",
"In the examples above we simply added multiple lines/points/bars/images \n",
"(collectively called artists in matplotlib) to a single plot.\n",
"To prettify this plots, we first need to know what all the features are called:\n",
"Based on this plot let's figure out what our first command of `plt.plot([1, 2, 3], [1.3, 4.2, 3.1])`\n",
"actually does:\n",
"\n",
"1. First it creates a figure and makes this the active figure. Being the active figure means that any subsequent commands will affect figure. You can find the active figure at any point by calling `plt.gcf()`.\n",
"2. Then it creates an Axes or Subplot in the figure and makes this the active axes. Any subsequent commands will reuse this active axes. You can find the active axes at any point by calling `plt.gca()`.\n",
"3. Finally it creates a Line2D artist containing the x-coordinates `[1, 2, 3]` and `[1.3, 4.2, 3.1]` ands adds this to the active axes.\n",
"4. At some later time, when actually creating the plot, matplotlib will also automatically determine for you a default range for the x-axis and y-axis and where the ticks should be.\n",
"\n",
"This concept of an \"active\" figure and \"active\" axes can be very helpful with a single plot, it can quickly get very confusing when you have multiple sub-plots within a figure or even multiple figures.\n",
"In that case we want to be more explicit about what sub-plot we want to add the artist to.\n",
"We can do this by switching from the \"procedural\" interface used above to the \"object-oriented\" interface.\n",
"The commands are very similar, we just have to do a little more setup.\n",
"For example, the equivalent of `plt.plot([1, 2, 3], [1.3, 4.2, 3.1])` is:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "19752271",
"metadata": {},
"outputs": [],
"source": [
"fig = plt.figure()\n",
"ax = fig.add_subplot()\n",
"ax.plot([1, 2, 3], [1.3, 4.2, 3.1])"
]
},
{
"cell_type": "markdown",
"id": "fe750f08",
"metadata": {},
"source": [
"Note that here we explicitly create the figure and add a single sub-plot to the figure.\n",
"We then call the `plot` function explicitly on this figure.\n",
"The \"Axes\" object has all of the same plotting command as we used above,\n",
"although the commands to adjust the properties of things like the title, x-axis, and y-axis are slighly different.\n",
"## Multiple plots (i.e., subplots)\n",
"As stated one of the strengths of the object-oriented interface is that it is easier to work with multiple plots. \n",
"While we could do this in the procedural interface:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7f35488a",
"metadata": {},
"outputs": [],
"source": [
"plt.subplot(221)\n",
"plt.title(\"Upper left\")\n",
"plt.subplot(222)\n",
"plt.title(\"Upper right\")\n",
"plt.subplot(223)\n",
"plt.title(\"Lower left\")\n",
"plt.subplot(224)\n",
"plt.title(\"Lower right\")"
]
},
{
"cell_type": "markdown",
"id": "490dd65c",
"metadata": {},
"source": [
"For such a simple example, this works fine. But for longer examples you would find yourself constantly looking back through the\n",
"code to figure out which of the subplots this specific `plt.title` command is affecting.\n",
"\n",
"The recommended way to this instead is:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b779ce08",
"metadata": {},
"outputs": [],
"source": [
"fig, axes = plt.subplots(nrows=2, ncols=2)\n",
"axes[0, 0].set_title(\"Upper left\")\n",
"axes[0, 1].set_title(\"Upper right\")\n",
"axes[1, 0].set_title(\"Lower left\")\n",
"axes[1, 1].set_title(\"Lower right\")"
]
},
{
"cell_type": "markdown",
"id": "15f4138d",
"metadata": {},
"source": [
"Here we use `plt.subplots`, which creates both a new figure for us and a grid of sub-plots. \n",
"The returned `axes` object is in this case a 2x2 array of `Axes` objects, to which we set the title using the normal numpy indexing.\n",
"\n",
"> Seaborn is great for creating grids of closely related plots. Before you spent a lot of time implementing your own have a look if seaborn already has what you want on their [gallery](https://seaborn.pydata.org/examples/index.html)\n",
"### Adjusting plot layout\n",
"The default layout of sub-plots often leads to overlap between the labels/titles of the various subplots (as above) or to excessive amounts of whitespace in between. We can often fix this by just adding `fig.tight_layout` (or `plt.tight_layout`) after making the plot:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ad25c7d6",
"metadata": {},
"outputs": [],
"source": [
"fig, axes = plt.subplots(nrows=2, ncols=2)\n",
"axes[0, 0].set_title(\"Upper left\")\n",
"axes[0, 1].set_title(\"Upper right\")\n",
"axes[1, 0].set_title(\"Lower left\")\n",
"axes[1, 1].set_title(\"Lower right\")\n",
"fig.tight_layout()"
]
},
{
"cell_type": "markdown",
"id": "c37f8dbe",
"metadata": {},
"source": [
"Uncomment `fig.tight_layout` and see how it adjusts the spacings between the plots automatically to reduce the whitespace.\n",
"If you want more explicit control, you can use `fig.subplots_adjust` (or `plt.subplots_adjust` to do this for the active figure).\n",
"For example, we can remove any whitespace between the plots using:"
"You can create more advanced grid layouts using [GridSpec](https://matplotlib.org/stable/tutorials/intermediate/gridspec.html).\n",
"An example taken from that website is:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "abd57aac",
"metadata": {},
"outputs": [],
"source": [
"fig = plt.figure(constrained_layout=True)\n",
"gs = fig.add_gridspec(3, 3)\n",
"f3_ax1 = fig.add_subplot(gs[0, :])\n",
"f3_ax1.set_title('gs[0, :]')\n",
"f3_ax2 = fig.add_subplot(gs[1, :-1])\n",
"f3_ax2.set_title('gs[1, :-1]')\n",
"f3_ax3 = fig.add_subplot(gs[1:, -1])\n",
"f3_ax3.set_title('gs[1:, -1]')\n",
"f3_ax4 = fig.add_subplot(gs[-1, 0])\n",
"f3_ax4.set_title('gs[-1, 0]')\n",
"f3_ax5 = fig.add_subplot(gs[-1, -2])\n",
"f3_ax5.set_title('gs[-1, -2]')"
]
},
{
"cell_type": "markdown",
"id": "dba57d95",
"metadata": {},
"source": [
"## Styling your plot\n",
"### Setting title and labels\n",
"You can edit a large number of plot properties by using the `Axes.set_*` interface.\n",
"We have already seen several examples of this above, but here is one more:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "777873ac",
"metadata": {},
"outputs": [],
"source": [
"fig, axes = plt.subplots()\n",
"axes.plot([1, 2, 3], [2.3, 4.1, 0.8])\n",
"axes.set_xlabel('xlabel')\n",
"axes.set_ylabel('ylabel')\n",
"axes.set_title('title')"
]
},
{
"cell_type": "markdown",
"id": "a4702249",
"metadata": {},
"source": [
"You can also set any of these properties by calling `Axes.set` directly:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2330c244",
"metadata": {},
"outputs": [],
"source": [
"fig, axes = plt.subplots()\n",
"axes.plot([1, 2, 3], [2.3, 4.1, 0.8])\n",
"axes.set(\n",
" xlabel='xlabel',\n",
" ylabel='ylabel',\n",
" title='title',\n",
")"
]
},
{
"cell_type": "markdown",
"id": "42c6eaa2",
"metadata": {},
"source": [
"> To match the matlab API and save some typing the equivalent commands in the procedural interface do not have the `set_` preset. So, they are `plt.xlabel`, `plt.ylabel`, `plt.title`. This is also true for many of the `set_` commands we will see below.\n",
"\n",
"You can edit the font of the text when setting the label:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f17bf9f6",
"metadata": {},
"outputs": [],
"source": [
"fig, axes = plt.subplots()\n",
"axes.plot([1, 2, 3], [2.3, 4.1, 0.8])\n",
"axes.set_xlabel(\"xlabel\", color='red')\n",
"axes.set_ylabel(\"ylabel\", fontsize='larger')"
]
},
{
"cell_type": "markdown",
"id": "8ae4d1f4",
"metadata": {},
"source": [
"### Editing the x- and y-axis\n",
"We can change many of the properties of the x- and y-axis by using `set_` commands.\n",
"\n",
"- The range shown on an axis can be set using `ax.set_xlim` (or `plt.xlim`)\n",
"- You can switch to a logarithmic (or other) axis using `ax.set_xscale('log')`\n",
"- The location of the ticks can be set using `ax.set_xticks` (or `plt.xticks`)\n",
"- The text shown for the ticks can be set using `ax.set_xticklabels` (or as a second argument to `plt.xticks`)\n",
"- The style of the ticks can be adjusted by looping through the ticks (obtained through `ax.get_xticks` or calling `plt.xticks` without arguments).\n",