{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Properly Sized Color Bars in Matplotlib\n",
"\n",
"[back to overview page](index.ipynb)\n",
"\n",
"By default, the size of color bars is computed to match the figure size.\n",
"However, in most cases I have seen, it would be more appropriate to scale the color bars to match the size of the actual plot.\n",
"\n",
"It looks wrong even in the official examples, e.g. http://matplotlib.org/examples/pylab_examples/colorbar_tick_labelling_demo.html\n",
"\n",
"If you want to skip all the boring explanations, you can jump right to [the solution](#The-Proper-Solution).\n",
"\n",
"You can also have a look at [my stackoverflow answer on the topic](http://stackoverflow.com/a/33505522/500098).\n",
"\n",
"As always, the information on this page might be outdated:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2019-07-26\r\n"
]
}
],
"source": [
"!date +%F"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is the date of the last change to this page. If it's older then half a year or a year, it is very likely to be outdated, so don't read it!"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"plt.rcParams['image.cmap'] = 'coolwarm'\n",
"plt.rcParams['image.origin'] = 'lower'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Please check if your local settings for the \"inline\" backend are meaningful, see [Default Values for Matplotlib's \"inline\" backend](matplotlib-inline-defaults.ipynb)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Some [dummy data](http://matplotlib.org/examples/pylab_examples/pcolor_demo.html):"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"def dummy_data(xmin, xmax):\n",
" ymin, ymax = -2, 2\n",
" x, y = np.meshgrid(np.arange(xmin, xmax, 0.1), np.arange(ymin, ymax, 0.1))\n",
" z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)\n",
" extent = x.min(), x.max(), y.min(), y.max()\n",
" return z, extent"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"z, extent = dummy_data(-3, 3)\n",
"zmax = np.max(np.abs(z))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Problem"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
"