{"nbformat": 4, "nbformat_minor": 1, "cells": [{"metadata": {}, "source": [" Matplotlib[\u00b6](#Matplotlib)\n--------------------------\n\n[ [back to top](#top) ]\n\n According to the [Matplotlib](https://matplotlib.org) website: \"Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shells, the Jupyter notebook, web application servers, and four graphical user interface toolkits.\" (Visual) examples can be found [here](https://matplotlib.org/tutorials/introductory/sample_plots.html) and [here](https://matplotlib.org/gallery/index.html) for inspiration. In addition, we will show some of Matplotlib's functionality in this tutorial.\n\n "], "cell_type": "markdown"}, {"metadata": {}, "outputs": [], "source": ["import numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline"], "execution_count": null, "cell_type": "code"}, {"metadata": {}, "source": [" Matplolib has *several* plotting capabilities. For example,\n\n * plot \u2014 plotting x and y data points\n * errorbar \u2014 plotting x and y data points with errorbars\n * hist \u2014 plotting histograms\n * hist2d \u2014 plotting 2D histograms\n * matshow \u2014 display a matrix\n * etc...\n "], "cell_type": "markdown"}, {"metadata": {}, "outputs": [], "source": ["x = np.linspace(0, 4*np.pi, 100)\ny = np.sin(x)"], "execution_count": null, "cell_type": "code"}, {"metadata": {}, "outputs": [], "source": ["plt.plot(x, y);"], "execution_count": null, "cell_type": "code"}, {"metadata": {}, "outputs": [], "source": ["x = np.linspace(0, 4*np.pi, 100)\ny1 = np.sin(x)\ny2 = np.cos(x)"], "execution_count": null, "cell_type": "code"}, {"metadata": {}, "outputs": [], "source": ["fig, ax = plt.subplots()\nax.plot(x, y1)\nax.plot(x, y2)\nplt.show()"], "execution_count": null, "cell_type": "code"}, {"metadata": {}, "outputs": [], "source": ["fig, ax = plt.subplots()\nax.plot(x, y1, label='Sine')\nax.plot(x, y2, label='Cosine')\nax.legend()\nplt.show()"], "execution_count": null, "cell_type": "code"}, {"metadata": {}, "outputs": [], "source": ["fig, ax = plt.subplots()\nax.plot(x, y1, label='Sine')\nax.plot(x, y2, label='Cosine')\nax.set_xlabel('x')\nax.set_ylabel('f(x)')\nax.grid()\nax.legend(title='Functions')\nplt.show()"], "execution_count": null, "cell_type": "code"}, {"metadata": {}, "outputs": [], "source": ["fig, ax = plt.subplots()\nax.plot(x, y1, label='Sine')\nax.plot(x, y2, label='Cosine')\nax.fill_between(x, y2, y1, color='C2', alpha=0.25)\nax.set_xlabel('x')\nax.set_ylabel('f(x)')\nax.grid()\nax.legend(title='Functions')\nplt.show()"], "execution_count": null, "cell_type": "code"}, {"metadata": {}, "source": [" Let's try to make some plots based on the text file people.txt that we created in the first part of these lectures. (If you lost it, you can download it [here](https://icecube.wisc.edu/~dvaneijk/IceCube_Bootcamp_2018/people.txt)).\n\n "], "cell_type": "markdown"}, {"metadata": {}, "outputs": [], "source": ["#!/usr/bin/env python\n\nf=open(\"people.txt\",'r+')\n\n# Reserve two python lists for the names and ages in the txt file\nnames = []\nages = []\n\n# Loop over the lines in the file and fill the lists\nfor line in f:\n names.append(line.split()[0])\n ages.append(int(line.split()[1]))\n\n# Make a plot\nfig, ax = plt.subplots(figsize = (8,5))\n\nbar_width = 0.75\nopacity = 0.6\n\nbars = ax.bar(names, ages, bar_width,\n alpha=opacity, color='r')\n\nax.set_xlabel('Name')\nax.set_ylabel('Age')\nax.set_title('Ages of people in people.txt')\nplt.show()"], "execution_count": null, "cell_type": "code"}, {"metadata": {}, "source": [" We could also make two data series for the men and women separately. We could (and should) have done that by adding another column 'gender' in the txt file, but let's take another approach in the example below where we use a dictionary instead.\n\n "], "cell_type": "markdown"}, {"metadata": {}, "outputs": [], "source": ["#!/usr/bin/env python\n\npeople = {'James':[24,'m'],'Jane':[40,'f'],'Sam':[12,'m'],'Ben':[1,'m'],'Debbie':[20,'f'],'Peggy':[30,'f'],\\\n 'Chuck':[67,'m'],'Mary':[8,'f'],'Buck':[30,'m'],'Burt':[100,'m']}\n# Loop over the lines in the file and fill the lists\nmale = []\nmale_ages = []\nfemale = []\nfemale_ages = []\n\nfor key,value in people.iteritems():\n if value[1] == 'm':\n male.append(key)\n male_ages.append(value[0])\n if value[1] == 'f':\n female.append(key)\n female_ages.append(value[0])\n\n# Make a plot\nfig, ax = plt.subplots(figsize = (8,5))\n\nbar_width = 0.75\nopacity = 0.6\n\nmale_bars = ax.bar(male, male_ages, bar_width,\n alpha=opacity, color='b')\n\nfemale_bars = ax.bar(female, female_ages, bar_width,\n alpha=opacity, color='r')\n\nax.set_xlabel('Name')\nax.set_ylabel('Age')\nax.set_title('Ages of people in people.txt')\nplt.show()"], "execution_count": null, "cell_type": "code"}, {"metadata": {}, "source": [" Finally, we can make a histogram of the ages, print out some statistics, and let one of the bins stand out by changing the color.\n\n "], "cell_type": "markdown"}, {"metadata": {}, "outputs": [], "source": ["#!/usr/bin/env python\n\nf=open(\"people.txt\",'r+')\n\n# Make a list of all the ages in the dataset using Python's list comprehension\nages = np.array([int(line.split()[1]) for line in f])\nmu = ages.mean()\nsigma = ages.std()\n\nprint 'Average age is {:.0f}'.format(mu)\nprint 'Standard deviation is {:.0f}'.format(sigma)\n\n# Make a plot\nfig, ax = plt.subplots(figsize = (8,5))\n\n# Bin the data using the ax.hist command\nn, bins, patches = ax.hist(ages, 10,color='b',alpha=0.6)\n \nax.set_xlabel('Age')\nax.set_ylabel('Number of people')\nax.set_title(r'Histogram of ages: $\\mu={:.0f}$, $\\sigma={:.0f}$'.format(mu,sigma))\nax.set_yticks([1,2,3,4])\nplt.setp(patches[-1], 'facecolor', 'g')\nplt.show()"], "execution_count": null, "cell_type": "code"}, {"metadata": {}, "source": [" Other Python packages to check out[\u00b6](#Other-Python-packages-to-check-out)\n--------------------------------------------------------------------------\n\n[ [back to top](#top) ]\n\n * [Scipy](https://www.scipy.org) The SciPy (Scientific Python) package extends the functionality of NumPy with a substantial collection of useful algorithms, like minimization, Fourier transformation, regression, and other applied mathematical techniques. You can import scipy into your program using any of the aforementioned methods using scipy as the package, however odds are your package of interest lies within a project which you need to import explicitly to use, see the examples below. I won't go into details on the use of scipy functions because there are just too many. You can find them on their documentation page and I have provided a list of some common functions below. Scipy and numpy work hand in hand so use scipy to preform operations on your arrays rather then writing them by hand.\n\t + scipy.stats - Everything statistics.\n\t + scipy.constants - Physical and mathematical constants\n\t + scipy.fftpack - Fourier transform\n\t + scipy.integrate - Integration routines\n\t + scipy.interpolate - Interpolation\n\t + scipy.linalg - Linear algebra routines\n\t + scipy.ndimage - n-dimensional image package\n\t + scipy.special - Any special mathematical functions\n\t \n * [Pandas](http://pandas.pydata.org) \u2014 High-performance data analysis toolkit\n * [Seaborn](http://seaborn.pydata.org/) \u2014 Statistical data visualization using Matplotlib\n * [Scikit-learn](http://scikit-learn.org/stable/) \u2014 Machine learning library\n * [Jupyter](http://jupyter.org/) \u2014 Document that combined code, markdown documentation, images, etc. Ideal for documenting an analysis.\n "], "cell_type": "markdown"}, {"metadata": {}, "source": [" Additional exercises[\u00b6](#Additional-exercises)\n==============================================\n\n#### If you're still up for it, here are some additional exercises :)[\u00b6](#If-you're-still-up-for-it,-here-are-some-additional-exercises-:))\n\n[ [back to top](#top) ]\n\n 2. Use the ipython terminal to prototype a function that prints the first 100 terms of the Fibonacci sequence. Save your lines of code to a file named fibscript.py so you can use it later.\n 4. Write a script called mcpi.py that calculates pi by drawing random numbers uniformly on the space x=(-1,1) y=(-1,1).\n\t * Hint: Write out the area of a circle and a square and take the ratio.\n\t * Super Hint: The number of things falling randomly in a given area are proportional to their area.\n\t \n 6. Write a script called peopletodict.py to make a dictionary from people.txt where the keys are the names and the values are the ages.\n "], "cell_type": "markdown"}], "metadata": {}}