Exercise4_9WalkthroughBokeh.ipynb 9.83 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction to Python Programming"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Walkthrough: Exercise 4.9 - Plotting with Bokeh"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First things first, we need to import the functions that we need from the third-party libraries, Pandas and Bokeh. We import all of Pandas, with the abbreviated namespace `pd`, and `figure`, `show` and `output_notebook` from `bokeh.plotting`. We use `output_notebook` here, to allow the plot to be displayed in this Jupyter Notebook - you might want to use `output_file` instead, which will result in the figure being rendered in an HTML file instead (see below). `figure` is used to construct the figure, and `show` is used to render the layout in the end. Speaking of layout, we import `gridplot` from `bokeh.io`, to create rows and columsn of the figures after we've created them. "
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
26
   "execution_count": null,
27 28 29 30 31 32
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
Toby Hodges's avatar
Toby Hodges committed
33
    "from bokeh.plotting import figure, show, output_notebook, output_file\n",
34 35 36 37 38 39 40 41 42 43 44 45
    "from bokeh.io import gridplot"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we need to read the data from the file into Python. Unlike in the matplotlib example, we will use a Pandas `DataFrame` here. (Note that this approach would work with matplotlib too - we're just choosing to introduce it at the same time as we start doing things with Bokeh.) We use the `read_table` function, with the `index_col` and `header` arguments, to read the tabular data into a dataframe."
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
46
   "execution_count": null,
47 48 49
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
50
   "outputs": [],
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
   "source": [
    "inputFile = 'speciesDistribution_tabular.txt'\n",
    "data = pd.read_table(inputFile, header=0, index_col=0)\n",
    "data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Great! Now we have all of our data loaded and arranged in the way that we need, we can move onto plotting."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we use `output_notebook()` to make sure that our plots can be displayed in this Notebook."
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
73
   "execution_count": null,
74 75 76
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
77
   "outputs": [],
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
   "source": [
    "output_notebook()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "_Note: to save the plot to a file instead, use:_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```Python\n",
    "output_file('my_amazing_plot.html') # give files descriptive names so you can easily identify them in future\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can start creating the indivual bar plots, one for each site. We want to display these plots all together, so we should start by storing them in a list. For each site we pull out the bar heights - this is the dataframe column corresponding to the site name; and the taxon names as a list created from the index column of the dataframe.\n",
    "\n",
104
    "Next, we create a figure object for the site, using the site name as the title, and setting the range for the x-axis as the taxon names. `tools=[]` disables the interactive tool bar for these plots. Finally, we call the `figure` object's `vbar` method to add the bars to the figure axes. The mid-points of the bars on the axis need to be labelled with the taxon names, so we construct a list comprehension* adding 0.5 to the index numbers along the axis. The heights of the bars are given as the column that we pulled out earlier. Once the figure is constructed, we add it to the list of plots."
105 106 107 108
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
109
   "execution_count": null,
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "plots = []\n",
    "for site in data.columns:\n",
    "    heights = data[site]\n",
    "    taxa = list(data.index)\n",
    "    fig = figure(plot_width=300, plot_height=200, title=site, x_range=taxa, tools=[])\n",
    "    fig.vbar(x=[n+0.5 for n in range(13)], \n",
    "       width=0.8, \n",
    "       bottom=0, \n",
    "       top=heights, \n",
    "       color='firebrick')\n",
    "    plots.append(fig)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The final step is to lay out and display the plots. Here, we will use the `gridplot` function from `bokeh.io`, but there are plenty of other options. Check out the documentation [here](http://bokeh.pydata.org/en/latest/docs/user_guide/layout.html)."
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
137
   "execution_count": null,
138 139 140
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
141
   "outputs": [],
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
   "source": [
    "layout = gridplot([[plots[0],plots[1]],\\\n",
    "                   [plots[2],plots[3]],\\\n",
    "                   [plots[4],plots[5]],\\\n",
    "                   [plots[6]]])\n",
    "show(layout)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As a bonus, let's colour the bars individually according to the taxon that they refer to. There are 13 taxa, which is a bit too large to avoid using some similar colours, so we use the Category20 color palette instead. Several palettes are available via the `bokeh.palettes` module. Choose which one you want, then specify how many colours you need when you use the palette in your plot(s)."
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
159
   "execution_count": null,
160 161 162 163 164 165 166 167 168 169
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from bokeh.palettes import Category20"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
170
   "execution_count": null,
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "plots = []\n",
    "for site in data.columns:\n",
    "    heights = data[site]\n",
    "    taxa = list(data.index)\n",
    "    fig = figure(plot_width=300, plot_height=200, title=site, x_range=taxa, tools=[])\n",
    "    fig.vbar(x=[n+0.5 for n in range(13)], \n",
    "       width=0.8, \n",
    "       bottom=0, \n",
    "       top=heights, \n",
    "       color=Category20[13])\n",
    "    plots.append(fig)"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
191
   "execution_count": null,
192 193 194
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
195
   "outputs": [],
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
   "source": [
    "layout = gridplot([[plots[0],plots[1]],\\\n",
    "                   [plots[2],plots[3]],\\\n",
    "                   [plots[4],plots[5]],\\\n",
    "                   [plots[6]]])\n",
    "show(layout)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### \\*Note on list comprehensions\n",
    "\n",
    "A list comprehension is a way of building up a list from a loop on the fly. For example, the following two code blocks are equivalent:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
215
   "execution_count": null,
216 217 218
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
219
   "outputs": [],
220 221 222 223 224 225 226 227 228 229
   "source": [
    "originals = range(10)\n",
    "squares = []\n",
    "for num in originals:\n",
    "    squares.append(num**2)\n",
    "print(squares)"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
230
   "execution_count": null,
231 232 233
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
234
   "outputs": [],
235 236 237 238 239 240 241 242 243 244 245 246 247 248
   "source": [
    "squares = [ x**2 for x in range(10) ]\n",
    "print(squares)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The list comprehension was necessary above, to align the x-axis labels correctly with the centre of each taxon bar. Another approach to get the same result is possible using the `arange` function from the `numpy` library, which provides an _array_ of numbers in the range requested. Consider the difference in output between the two blocks below:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
249
   "execution_count": null,
250 251 252
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
253
   "outputs": [],
254 255 256 257 258 259 260 261
   "source": [
    "some_numbers = list(range(2, 20)) # a standard list object\n",
    "print(some_numbers)\n",
    "some_numbers + 0.5"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
262
   "execution_count": null,
263 264 265
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
266
   "outputs": [],
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
   "source": [
    "from numpy import arange\n",
    "some_numbers = arange(2, 20)\n",
    "some_numbers + 0.5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So, if we wanted to, we could use `arange` to create our plots as follows:"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
282
   "execution_count": null,
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "plots = []\n",
    "for site in data.columns:\n",
    "    heights = data[site]\n",
    "    taxa = list(data.index)\n",
    "    fig = figure(plot_width=300, plot_height=200, title=site, x_range=taxa, tools=[])\n",
    "    fig.vbar(x=arange(13)+0.5, \n",
    "       width=0.8, \n",
    "       bottom=0, \n",
    "       top=heights, \n",
    "       color=Category20[13])\n",
    "    plots.append(fig)"
   ]
  },
  {
   "cell_type": "code",
Toby Hodges's avatar
Toby Hodges committed
303
   "execution_count": null,
304 305 306
   "metadata": {
    "collapsed": false
   },
Toby Hodges's avatar
Toby Hodges committed
307
   "outputs": [],
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
   "source": [
    "layout = gridplot([[plots[0],plots[1]],\\\n",
    "                   [plots[2],plots[3]],\\\n",
    "                   [plots[4],plots[5]],\\\n",
    "                   [plots[6]]])\n",
    "show(layout)"
   ]
  }
 ],
 "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.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}