{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Plotting\n", "\n", "The output we've created so far from our program has simply\n", "been printing out text. However, if you are using Python\n", "for data science, statistics, applied mathematics, or many\n", "other applications of computing, you often want to do more\n", "than just compute and print one or more values. Typically,\n", "you may want to visualize the result of your simulation,\n", "computation, or analysis. To visualize results, we\n", "will make use of Python libraries that allow for easy\n", "creation of visualizations.\n", "\n", "\n", "## Libraries\n", "Up until now, we've focused primarily on the basics of Python -- \n", "knowing and using the\n", "fundamental constructs available in Python and understanding how\n", "to combine them to solve a problem computationally. While this\n", "fundamental understanding is crucial, in Python it's very\n", "common to make use of other libraries that:\n", "* provide specialized functionality not included in base python\n", "* make other tasks that could be done with base python easier\n", "\n", "We've seen a couple of libraries, namely `math` and `random`\n", "already. These our both examples of libraries included\n", "in base Python. However, one of the great things about Python\n", "for applied computing is the sheer number of other, specialized\n", "libraries available. As of 2020, there are over 250,000 projects\n", "available for Python on the Python Package Index -- the standard\n", "repository for distributing libraries. On most cloud based systems\n", "for running Python (like CoCalc or Colab), many of the most\n", "popular libraries are already installed. So, to use them we\n", "simply type `import libraryname`. In some cases, if the library\n", "name is really long, you may see an alternate form of this\n", "import statement: `import libraryname as someshortname`, where\n", "`someshortname` is typically a 2-5 letter abbreviation for the library's\n", "name.\n", "\n", "## Matplotlib Library\n", "\n", "The most common library used for visualizing results in Python\n", "is Matplotlib. It is great for producing a wide variety of \n", "visualizations with combinations of:\n", "* line and scatter plots\n", "* bar charts and histograms\n", "* box plots\n", "* contour plots\n", "* vector fields\n", "* images\n", "* heat maps\n", "* simple plot animations\n", "* simple 3D plots\n", "\n", "Any plot can be customized with labels, legends, colors, annotations,\n", "and other stylistic choices to allow you to create professional\n", "quality visualizations.\n", "\n", "### Help with Matplotlib\n", "This will walk through and demonstrate a variety of plots\n", "you can do with matplotlib, but there are far more than can\n", "be covered here.\n", "Matplotlib has good\n", "[documentation](https://matplotlib.org/api/pyplot_api.html).\n", "and a really large, great\n", "[gallery of examples](https://matplotlib.org/1.5.1/gallery.html)\n", "that illustrates plots and the code used to create the plots.\n", "Often, it is helpful to find an example in the gallery of what\n", "sort of plot you are looking for and then view the code to create\n", "the plot and adapt it to your specific use.\n", "\n", "### Importing\n", "To get started with matplotlib, we first need to import it.\n", "With matplotlib, the library consists of multiple modules (essentially multiple small parts). This is something we didn't see with\n", "the `random` or `math` libraries. To access functions within a\n", "specific library in a module, we would need to call them with\n", "`libraryname.modulename.functionname()`. As you can imagine\n", "this can get quite long and be intrusive to type. Instead,\n", "if you are going to access primarily functions from one module,\n", "we can import it with `import libraryname.modulename as shortname`.\n", "Then, we can just use `shortname.functionname()` when we wish\n", "to call a function. For matplotlib, you typically really only\n", "need to call functions from the `pyplot` module, so we use the\n", "following import statement\n", "```\n", "import matplotlib.pyplot as plt\n", "```\n", "The choice of `plt` is optional, but is typically considered\n", "the standard convention for `matplotlib`. Most major libraries\n", "have standard short names that are used by the vast majority of\n", "people that write code, and sticking with the standard makes it\n", "easier for others to read your code.\n", "\n", "In jupyter notebooks (like this one), we typically add a\n", "\"magic command\" that makes the plots fit a little nicer\n", "directly in the notebooks. Magic commands are lines\n", "that start with `%`. The magic command\n", "typically used with matplotlib is\n", "```\n", "%matplotlib inline\n", "```\n", "\n", "We'll start by running both the magic command and our import statement." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Plotting Overview\n", "There are technically two different ways to interact\n", "with matplotlib:\n", "1. pyplot interface: Calling a function makes some\n", " change to the current figure such as:\n", " * create a new figure (or switch the current figure)\n", " * add a plot to the figure\n", " * plot some lines in current plot (\"axes\")\n", "2. object oriented API: This is a more formal approach\n", " that explicitly creates \"axes\" objects and calls their\n", " methods.\n", "We'll focus on (1), but you may see (2) if you look at\n", "other resources or the matplotlib gallery.\n", "\n", "### Standard Line/Scatter Plot\n", "The simplest way to plot is to use the `plot` function.\n", "This function can be called in many different ways (because\n", "many of the arguments are optional). Some of the\n", "most common are:\n", "* `plt.plot(yvals)` - takes list or array of $y$-values, assumes\n", " the $x$-values are integers ranging from 0 to `len(yvals)-1`\n", "* `plt.plot(xvals,yvals)` - plots line of points given by y versus x\n", " for list/array of $y$-values and $x$-values\n", "* `plt.plot(xvals, yvals, stylestring)` - same as previous but allows\n", " to customize line style by specifying color, whether the points should\n", " be marked with dots, whether they should be connected by a line, etc.\n", "There are also many other arguments you can pass as keyword arguments to `plot`.\n", "\n", "#### Starting Simple\n", "Let's start by looking at the simplest example by plotting\n", "the population (from the census data) in Detroit from\n", "$1910, 1920, \\ldots, 2000, 2010$." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "detroit_populations = [465766, 993678, 1568662, 1623452, 1849568, 1670144, 1511482, 1203339, 1027974, 951270, 713777]\n", "plt.plot(detroit_populations)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that this is just the population data, with the $x$-axis\n", "ranging from 0 to 10. We can also provide $x$-values\n", "as well when calling `plt.plot`. Since we know the\n", "years start at 1910 and go up to 2010 by 10 each time,\n", "we can easily make the list of years with `range`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "detroit_years = list(range(1910,2011,10))\n", "\n", "plt.plot(detroit_years, detroit_populations)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Changing Line Style and Color\n", "That plot looks okay, but a little plain. This\n", "is because it is the default plot style to simply\n", "connect the data points with a line.\n", "You can make it look better by customizing the\n", "color, line style, line width, etc. Some of the\n", "most common keyword arguments to modify the style\n", "are:\n", "* color: change color of line, can be abbreviated as c\n", " * `'r'` = red\n", " * `'b'` = blue\n", " * `'m'` = magenta\n", " * `'c'` = cyan\n", " * `'g'` = green\n", " * `'k'` = black\n", " * `'y'` = yellow\n", "* marker: marker to use for data points:\n", " * `'x'` = letter x\n", " * `'+'` = plus sign\n", " * `'o'` = normal dot\n", " * `'.'` = small dot\n", " * `'s'` = square\n", " * `''` = no marker\n", "* linestyle: how to display line connecting points\n", " * `'-'` = solid line\n", " * `':'` = dotted line\n", " * `'--'` = dashed line\n", " * `'-.'` = alternating dash-dot\n", " * `''` = no line between data points\n", "* linewidth: width of line, default value is 1.5, larger values are thicker lines\n", "* markersize: size of marker, default value is 6, larger values are larger markers\n", "\n", "The full list of arguments to plot can be seen in the\n", "[documentation for the plot function](https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.plot.html).\n", "\n", "Let's look at an example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "detroit_years = list(range(1910,2011,10))\n", "\n", "plt.plot(detroit_years, detroit_populations, color='c', marker='o', linestyle='--', linewidth=2.5, markersize=8)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since these are common, they can often be abbreviated in a couple of ways:\n", "1. shortened keyword:\n", " * can use `c=` instead of `color=`\n", " * can use `ls=` instead of `linestyle=`\n", " * can use `lw=` instead of `linewidth=`\n", " * can use `ms=` instead of `markersize=`\n", "2. provide a shorthand format string:\n", " * allows to specify color, marker, and linestyle in one argument\n", " * first character = color\n", " * second character = marker\n", " * third character = linestyle\n", " * provided as a short string directly after the data arguments\n", "\n", "For example, using the shortened keywords:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.plot(detroit_years, detroit_populations, c='c', marker='o', ls='--', lw=2.5, ms=8)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To generate the same figure using a shorthand format string, \n", "we can use:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.plot(detroit_years, detroit_populations, 'co--', lw=2.5, ms=8)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Adding Titles and Labels\n", "\n", "The previous plots had no labels, which really is\n", "not very helpful if you are trying to create useful,\n", "professional looking illustrations. We can\n", "add labels and a title to any matplotlib figure\n", "(including other types of charts) with:\n", "\n", "* `plt.xlabel('desired x-axis label')`\n", "* `plt.ylabel('desired y-axis label')`\n", "* `plt.title('desired title')`\n", "\n", "Let's look at adding labels to our previous plot:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.plot(detroit_years, detroit_populations, 'co--', lw=2.5, ms=8)\n", "plt.xlabel('census year')\n", "plt.ylabel('population')\n", "plt.title('Detroit Census Population')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Multiple Lines\n", "\n", "To add more than one line to a plot, you can\n", "simply make multiple calls to `plt.plot()` with\n", "the different data (and potentially different styles)\n", "you wish to plot. However, any time you plot\n", "multiple lines on a single plot, you should include\n", "a legend to distinguish the different lines.\n", "To indicate the line name that should be used\n", "in the legend, we can pass\n", "one additional keyword argument, `label`, to the\n", "call to the `plot` function. Then,\n", "we tell matplotlib to put a legend on our plot by\n", "calling `plt.legend()`. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "chicago_populations = [2185283, 2701705, 3376438, 3396808, 3620962, 3550404, 3366957, 3005072, 2783911, 2896016, 2695598]\n", "chicago_years = list(range(1910,2011,10))\n", "plt.plot(detroit_years, detroit_populations, 'co--', label='Detroit')\n", "plt.plot(chicago_years, chicago_populations, 'ms-', label='Chicago')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sometimes the default location for the legend\n", "may not be ideal (covering an important part\n", "of the plot). We can pass an optional keyword\n", "argument, `loc` to `plt.legend()` to specify\n", "where in the plot the legend should be placed.\n", "The full list of locations is available in the\n", "[legend documentation](https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.legend.html). One of the most\n", "useful choices for location is `'best'`, which\n", "attempts to identify the best of the nine possible\n", "locations." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "chicago_populations = [2185283, 2701705, 3376438, 3396808, 3620962, 3550404, 3366957, 3005072, 2783911, 2896016, 2695598]\n", "chicago_years = list(range(1910,2011,10))\n", "plt.plot(detroit_years, detroit_populations, 'co--', label='Detroit')\n", "plt.plot(chicago_years, chicago_populations, 'mo-', label='Chicago')\n", "plt.legend(loc='upper left')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Other Axis Scales\n", "\n", "All of these plots used linear axis scales. Sometimes,\n", "you may want to visualize something using logarithmic\n", "scales on one or both of the axes. The choice of axis\n", "scale is typically dependent on the data and what you hope\n", "to show.\n", "\n", "For instance, much of the behavior in\n", "data that behaves like exponential growth is obscured\n", "on a plot with linear axes. Data that grows exponentially\n", "is often better illustrated on a semilog scale with a linear\n", "$x$-axis and a logarithmic $y$-axis.\n", "\n", "Similarly, if your data follows a power law, the data\n", "will appear as a straight line on a plot with logarithmic\n", "scales on both axes.\n", "\n", "We can create visualizations in matplotlib with other\n", "axis scales by replacing `plt.plot` with one of the\n", "following functions:\n", "\n", "* `plt.semilogx(xvals, yvals)` = logarithmic $x$-axis and linear\n", " $y$-axis\n", "* `plt.semilogy(xvals, yvals)` = linear $x$-axis and\n", " logarithmic $y$-axis\n", "* `plt.loglog(xvals, yvals)` = logarithmic $x$-axis and\n", " logarithmic $y$-axis\n", "\n", "These functions can also take the same additional arguments\n", "as `plot` to specify line formatting." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ys = [2**i for i in range(1,14)]\n", "xs = [i for i in range(1,14)]\n", "plt.semilogy(xs, ys,'bo-')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Bar Charts\n", "\n", "Matplotlib also provides the ability to \n", "create bar charts. To create a bar chart,\n", "we can use one of two functions:\n", "* `plt.bar(names, values)` - vertical bar plot\n", "* `plt.barh(names, values)` - horizontal bar plot\n", "\n", "#### Examples" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sec8housing = [5528, 1141, 1386, 963, 981, 2271, 1427]\n", "cities = ['Detroit', 'Saginaw', 'Plymouth', 'Flint', 'Wyoming', 'Grand Rapids', 'Lansing']\n", "plt.bar(cities, sec8housing)\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sec8housing = [5528, 1141, 1386, 963, 981, 2271, 1427]\n", "cities = ['Detroit', 'Saginaw', 'Plymouth', 'Flint', 'Wyoming', 'Grand Rapids', 'Lansing']\n", "plt.barh(cities, sec8housing)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As with `plot`, there are other optional arguments\n", "that can be used to modify the plot, such as changing\n", "colors, bar width, opacity, $y$-axis scale, edge color, etc. \n", "The full list of\n", "available options to `plt.bar()` can be found in the\n", "[documentation for bar function](https://matplotlib.org/3.3.2/api/_as_gen/matplotlib.pyplot.bar.html).\n", "\n", "As with `plot`, we can also add titles and labels with the same functions\n", "we used previously.\n", "\n", "#### Example" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.bar(cities, sec8housing, color='c', alpha=0.3, width=.5, edgecolor='k', lw=1.3)\n", "plt.title('Section 8 Housing in MI Cities')\n", "plt.xlabel('Quantity')\n", "plt.ylabel('City')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Stacked Bar Charts\n", "\n", "If you wish to display multiple pieces of quantitative\n", "data that make sense to present both individually\n", "and in total, it can make sense to use a stacked\n", "bar chart. We can create a stacked\n", "bar chart in matplotlib by calling `plt.bar()` multiple\n", "times with the different data, using the `bottom` keyword\n", "argument when plotting the top bars to specify\n", "that the bottom of the top bars should be at the values of\n", "the bottom data." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.bar(cities, sec8housing, color='r', alpha=0.6, label='section 8')\n", "lowrent = [4391, 605, 108, 1248, 197, 447, 834]\n", "plt.bar(cities, lowrent, color='c', alpha=0.5, bottom=sec8housing, label='low rent')\n", "plt.title('Low Rent and Section 8 Housing in MI Cities')\n", "plt.xlabel('Quantity')\n", "plt.ylabel('City')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many other functions that can be called to slightly\n", "modify the appearance of a plot, far more than we can cover\n", "here. For instance, in the above plot, the city names are overlapping.\n", "One way we can correct that is to rotate the tick labels\n", "by calling `plt.xticks()`. This is a multi-purpose function\n", "that works for all plot types including line/scatter plots, bar charts, etc.\n", "and allows the tick labels and rotation to be customized.\n", "\n", "For the above plot, it would be very helpful if the tick\n", "labels (cities) were rotated so they did not overlap." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.bar(cities, sec8housing, color='r', alpha=0.6, label='section 8')\n", "lowrent = [4391, 605, 108, 1248, 197, 447, 834]\n", "plt.bar(cities, lowrent, color='c', alpha=0.5, bottom=sec8housing, label='low rent')\n", "plt.title('Low Rent and Section 8 Housing in MI Cities')\n", "plt.xlabel('Quantity')\n", "plt.ylabel('City')\n", "plt.legend()\n", "plt.xticks(rotation=45)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Histograms\n", "\n", "Histograms are very similar to bar charts, but differ in\n", "that they display the number of values in each of a set of\n", "bins. Matplotlib will both compute the bins and visualize\n", "the histogram with:\n", "* `plt.hist(values)`\n", "* `plt.hist(values, bins)`\n", "The second call is exactly the same as the first except\n", "it allows you to specify the bins by choosing:\n", "* the number of bins if `bins` is an integer\n", "* the bin edges if `bins` is a list\n", "* the binning strategy if `bins` is a string\n", "As with `bar`, there are many different keyword arguments\n", "you can pass when calling the function to customize" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Example" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "monthly_precip_gr = [2.73,1.99,2.9,3.43,2.23,4.05,5.96,4.36,3.92,3.41,7.32,7.13,2.62,4.04,3.65,1.2,3.27,4.09,4.22,2.84,4.75,2.6,3.07,2.67]\n", "plt.hist(monthly_precip_gr)\n", "plt.title('Histogram of Total Monthly Precipitation in Grand Rapids')\n", "plt.xlabel('Precipitation (inches)')\n", "plt.ylabel('Frequency')\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Boxplot\n", "\n", "Box and whisker plots are very common in statistics.\n", "We can create a box plot with the `boxplot` function,\n", "with the list of values:\n", "* `plt.boxplot(values)` - vertical boxplot\n", "* `plt.boxplot(values, vert=False)` - horizontal boxplot\n", "\n", "#### Examples" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "rent_prices = [350, 400, 450, 425, 375, 500, 480, 550, 650, 700]\n", "plt.boxplot(rent_prices)\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "rent_prices_allendale = [350, 400, 450, 425, 375, 500, 480, 550, 650, 700]\n", "plt.boxplot(rent_prices_allendale, vert=False)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `values` can be a lists of lists to plot more than one\n", "boxplot on the same figure. You can also specify a label\n", "(to replace the 1 on the left in the previous plot), which\n", "is used to label the different boxplots when there is\n", "more than one. For example," ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "rent_prices_allendale = [350, 400, 450, 425, 375, 500, 480, 550, 650, 700]\n", "rent_prices_gr = [500, 550, 700, 850, 1000, 750, 600, 650, 800]\n", "all_prices = [rent_prices_allendale, rent_prices_gr]\n", "cities = ['Allendale', 'Grand Rapids']\n", "plt.boxplot(all_prices, vert=False, labels=cities)\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Images\n", "Matplotlib also has some basic functionality for:\n", "* loading images\n", "* interpolating pixels (think smoothing)\n", "* visualizing images in different colormaps\n", "\n", "More advanced image manipulation typically relies\n", "on additional advanced pages we have not discussed\n", "yet, so for now we'll just look at how to load\n", "and show an image.\n", "\n", "We can load an image with the `imread(filename)` function,\n", "where `filename` is a string containing the name of the file.\n", "This is the first (and only) function we'll look at that is\n", "not in `matplotlib.pyplot`. This function is instead\n", "in the `image` module, so we must first import `matplotlib.image`. Since this is also longer than we\n", "wish to type, we import it as `mpimg`.\n", "\n", "Once the image is loaded, we can call `plt.imshow` with\n", "the loaded image as an argument to visualize it. We\n", "can optionally pass in values for the keyword arguments\n", "`cmap` or `interpolation` to change how the image is displayed.\n", "\n", "#### Example" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.image as mpimg\n", "img = mpimg.imread('../media/dog.jpg')\n", "plt.imshow(img)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that above we used what's known as a *path* in place of the filename. We saw these previously when reading in files. This one is slightly different in that the folder `media` is not in our current folder, but one level above. We indicate one level above by adding `../` to the start, followed by the folder name it's in, followed by the filename itself." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Multiple Plots in One Figure\n", "\n", "Each of the previous visualizations has been a single plot\n", "(with potentially a couple of lines, but all on a single \"axis\"\n", "in matplotlib terminology). Often, we want multiple subplots\n", "in a single figure (so they are still grouped, but not plotted\n", "on the same $x$-$y$ axis). To do this, we first create a \"figure\"\n", "by calling `plt.figure()`. We've been working with a \"figure\" all along,\n", "just not one we explicitly created." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Optionally, we could have passed a specific figure number as an argument\n", "to `plt.figure()`, which can be useful if you are switching between figures\n", "you wish to plot on. When given a figure number, if the figure already exists\n", "it will be made active, otherwise a new figure will be created.\n", "\n", "Once we have a figure, we need to add \"subplots\" (aka the individual\n", "$x$-$y$ axes we want to plot on). We specify the subplot we want to make active\n", "by calling \n", "```\n", "plt.subplot(nrows, ncols, index)\n", "```\n", "where:\n", "* `nrows` is the number of rows of subplots we wish to have\n", "* `ncols` is the number of columns of subplots we wish to have\n", "* `index` is the index of the subplot we want to make active. `index` starts\n", " at 1 in the upper left and increases going left-to-right and top-to-bottom (like\n", " reading a book).\n", "\n", "Once a given subplot is active, we simply call the desired plotting function\n", "to create the desired type of visualizations. The visualization types (aka plotting\n", "function) can be the same or different in each subplot.\n", "\n", "**Note: often the axis labels end up overlapping. This can almost always be fixed\n", "by calling `plt.tight_layout()` at the end.**\n", "\n", "#### Example\n", "\n", "Consider the population data for Detroit and Chicago. Instead of plotting\n", "both of the on the same axis, we could choose to plot them on separate axes in\n", "the same figure." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create the figure\n", "plt.figure()\n", "\n", "# Plot Detroit Data\n", "plt.subplot(2,1,1) # 2 rows, 1 column, 1st axis\n", "plt.xlabel('Census Year')\n", "plt.ylabel('Population')\n", "plt.title(\"Detroit Population Over Time\")\n", "plt.plot(detroit_years, detroit_populations, 'co--', label='Detroit')\n", "\n", "# Plot Chicago Data\n", "plt.subplot(2,1,2) # 2 rows, 1 column, 2nd axis\n", "plt.xlabel('Census Year')\n", "plt.ylabel('Population')\n", "plt.title(\"Chicago Population Over Time\")\n", "plt.plot(chicago_years, chicago_populations, 'mo--', label='Chicago')\n", "\n", "plt.tight_layout() # Important for spacing\n", "plt.show()" ] } ], "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.8.6" } }, "nbformat": 4, "nbformat_minor": 4 }