{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "IyWDKt1wJhjq" }, "source": [ "# Data Types, Graphical Marks, and Visual Encoding Channels\n", "\n", "A visualization represents data using a collection of _graphical marks_ (bars, lines, points, etc.). The attributes of a mark — such as its position, shape, size, or color — serve as _channels_ through which we can encode underlying data values." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With a basic framework of _data types_, _marks_, and _encoding channels_, we can concisely create a wide variety of visualizations. In this notebook, we explore each of these elements and show how to use them to create custom statistical graphics.\n", "\n", "_This notebook is part of the [data visualization curriculum](https://github.com/uwdata/visualization-curriculum)._" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "colab": {}, "colab_type": "code", "id": "Y5K12kFBKE6v" }, "outputs": [], "source": [ "import pandas as pd\n", "import altair as alt" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "dkfRE2_2KOZ9" }, "source": [ "## Global Development Data\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "LbfvKf2tzCmb" }, "source": [ "We will be visualizing global health and population data for a number of countries, over the time period of 1955 to 2005. The data was collected by the [Gapminder Foundation](https://www.gapminder.org/) and shared in [Hans Rosling's popular TED talk](https://www.youtube.com/watch?v=hVimVzgtD6w). If you haven't seen the talk, we encourage you to watch it first!\n", "\n", "Let's first load the dataset from the [vega-datasets](https://github.com/vega/vega-datasets) collection into a Pandas data frame." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "colab": {}, "colab_type": "code", "id": "cMgPRofkJHJP" }, "outputs": [], "source": [ "from vega_datasets import data as vega_data\n", "data = vega_data.gapminder()" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ioAtaF9P0IMX" }, "source": [ "How big is the data?" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "id": "oM-Lodk_KK8T", "outputId": "134a2f4a-c15d-4fcd-fd93-49b26a4f5e30" }, "outputs": [ { "data": { "text/plain": [ "(693, 6)" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data.shape" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "spJtZFQN0KCQ" }, "source": [ "693 rows and 6 columns! Let's take a peek at the data content:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 204 }, "colab_type": "code", "id": "SpB2dH0JKVJe", "outputId": "ec103505-4d8f-4310-a6e1-7eea3d789c28" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
yearcountryclusterpoplife_expectfertility
01955Afghanistan0889120930.3327.7
11960Afghanistan0982945031.9977.7
21965Afghanistan01099788534.0207.7
31970Afghanistan01243062336.0887.7
41975Afghanistan01413201938.4387.7
\n", "
" ], "text/plain": [ " year country cluster pop life_expect fertility\n", "0 1955 Afghanistan 0 8891209 30.332 7.7\n", "1 1960 Afghanistan 0 9829450 31.997 7.7\n", "2 1965 Afghanistan 0 10997885 34.020 7.7\n", "3 1970 Afghanistan 0 12430623 36.088 7.7\n", "4 1975 Afghanistan 0 14132019 38.438 7.7" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data.head(5)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ZpJ2OTZbY3Kf" }, "source": [ "For each `country` and `year` (in 5-year intervals), we have measures of fertility in terms of the number of children per woman (`fertility`), life expectancy in years (`life_expect`), and total population (`pop`).\n", "\n", "We also see a `cluster` field with an integer code. What might this represent? We'll try and solve this mystery as we visualize the data!" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "nTSCOwsEvo15" }, "source": [ "Let's also create a smaller data frame, filtered down to values for the year 2000 only:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "colab": {}, "colab_type": "code", "id": "kCVTdUK2Le_M" }, "outputs": [], "source": [ "data2000 = data.loc[data['year'] == 2000]" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 204 }, "colab_type": "code", "id": "mOLR5Nh-MLWm", "outputId": "8629f998-e723-4b92-9a95-f0df3c9843a8" }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
yearcountryclusterpoplife_expectfertility
92000Afghanistan02389819842.1297.4792
202000Argentina33749772874.3402.3500
312000Aruba36953973.4512.1240
422000Australia41916462080.3701.7560
532000Austria1811341378.9801.3820
\n", "
" ], "text/plain": [ " year country cluster pop life_expect fertility\n", "9 2000 Afghanistan 0 23898198 42.129 7.4792\n", "20 2000 Argentina 3 37497728 74.340 2.3500\n", "31 2000 Aruba 3 69539 73.451 2.1240\n", "42 2000 Australia 4 19164620 80.370 1.7560\n", "53 2000 Austria 1 8113413 78.980 1.3820" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data2000.head(5)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "xyIb1bzLJgG-" }, "source": [ "## Data Types\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "vyj1xBF2NTY6" }, "source": [ "The first ingredient in effective visualization is the input data. Data values can represent different forms of measurement. What kinds of comparisons do those measurements support? And what kinds of visual encodings then support those comparisons?\n", "\n", "We will start by looking at the basic data types that Altair uses to inform visual encoding choices. These data types determine the kinds of comparisons we can make, and thereby guide our visualization design decisions.\n", "\n", "### Nominal (N)\n", "\n", "*Nominal* data (also called *categorical* data) consist of category names. \n", "\n", "With nominal data we can compare the equality of values: *is value A the same or different than value B? (A = B)*, supporting statements like “A is equal to B” or “A is not equal to B”.\n", "In the dataset above, the `country` field is nominal.\n", "\n", "When visualizing nominal data we should readily be able to see if values are the same or different: position, color hue (blue, red, green, *etc.*), and shape can help. However, using a size channel to encode nominal data might mislead us, suggesting rank-order or magnitude differences among values that do not exist!\n", "\n", "### Ordinal (O)\n", "\n", "*Ordinal* data consist of values that have a specific ordering.\n", "\n", "With ordinal data we can compare the rank-ordering of values: *does value A come before or after value B? (A < B)*, supporting statements like “A is less than B” or “A is greater than B”.\n", "In the dataset above, we can treat the `year` field as ordinal.\n", "\n", "When visualizing ordinal data, we should perceive a sense of rank-order. Position, size, or color value (brightness) might be appropriate, where as color hue (which is not perceptually ordered) would be less appropriate.\n", "\n", "### Quantitative (Q)\n", "\n", "With *quantitative* data we can measure numerical differences among values. There are multiple sub-types of quantitative data:\n", "\n", "For *interval* data we can measure the distance (interval) between points: *what is the distance to value A from value B? (A - B)*, supporting statements such as “A is 12 units away from B”.\n", "\n", "For *ratio* data the zero-point is meaningful and so we can also measure proportions or scale factors: *value A is what proportion of value B? (A / B)*, supporting statements such as “A is 10% of B” or “B is 7 times larger than A”.\n", "\n", "In the dataset above, `year` is a quantitative interval field (the value of year \"zero\" is subjective), whereas `fertility` and `life_expect` are quantitative ratio fields (zero is meaningful for calculating proportions).\n", "Vega-Lite represents quantitative data, but does not make a distinction between interval and ratio types.\n", "\n", "Quantitative values can be visualized using position, size, or color value, among other channels. An axis with a zero baseline is essential for proportional comparisons of ratio values, but can be safely omitted for interval comparisons.\n", "\n", "### Temporal (T)\n", "\n", "*Temporal* values measure time points or intervals. This type is a special case of quantitative values (timestamps) with rich semantics and conventions (i.e., the [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian_calendar)). The temporal type in Vega-Lite supports reasoning about time units (year, month, day, hour, etc.), and provides methods for requesting specific time intervals.\n", "\n", "Example temporal values include date strings such as `“2019-01-04”` and `“Jan 04 2019”`, as well as standardized date-times such as the [ISO date-time format](https://en.wikipedia.org/wiki/ISO_8601): `“2019-01-04T17:50:35.643Z”`.\n", "\n", "There are no temporal values in our global development dataset above, as the `year` field is simply encoded as an integer. For more details about using temporal data in Altair, see the [Times and Dates documentation](https://altair-viz.github.io/user_guide/times_and_dates.html).\n", "\n", "### Summary\n", "\n", "These data types are not mutually exclusive, but rather form a hierarchy: ordinal data support nominal (equality) comparisons, while quantitative data support ordinal (rank-order) comparisons.\n", "\n", "Moreover, these data types do _not_ provide a fixed categorization. Just because a data field is represented using a number doesn't mean we have to treat it as a quantitative type! For example, we might interpret a set of ages (10 years old, 20 years old, etc) as nominal (underage or overage), ordinal (grouped by year), or quantitative (calculate average age).\n", "\n", "Now let's examine how to visually encode these data types!\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "yaz3tS2RKf03" }, "source": [ "## Encoding Channels\n", "\n", "At the heart of Altair is the use of *encodings* that bind data fields (with a given data type) to available encoding *channels* of a chosen *mark* type. In this notebook we'll examine the following encoding channels:\n", "\n", "- `x`: Horizontal (x-axis) position of the mark.\n", "- `y`: Vertical (y-axis) position of the mark.\n", "- `size`: Size of the mark. May correspond to area or length, depending on the mark type.\n", "- `color`: Mark color, specified as a [legal CSS color](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).\n", "- `opacity`: Mark opacity, ranging from 0 (fully transparent) to 1 (fully opaque).\n", "- `shape`: Plotting symbol shape for `point` marks.\n", "- `tooltip`: Tooltip text to display upon mouse hover over the mark.\n", "- `order`: Mark ordering, determines line/area point order and drawing order.\n", "- `column`: Facet the data into horizontally-aligned subplots.\n", "- `row`: Facet the data into vertically-aligned subplots.\n", "\n", "For a complete list of available channels, see the [Altair encoding documentation](https://altair-viz.github.io/user_guide/encoding.html)." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "vujZA4b6OCRC" }, "source": [ "### X\n", "\n", "The `x` encoding channel sets a mark's horizontal position (x-coordinate). In addition, default choices of axis and title are made automatically. In the chart below, the choice of a quantitative data type results in a continuous linear axis scale:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 87 }, "colab_type": "code", "id": "nswya-ToLaRP", "outputId": "2a958755-7f70-4a86-ab6f-2cfb24ad7231" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point().encode(\n", " alt.X('fertility:Q')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "WwQuuyKUOElr" }, "source": [ "### Y\n", "\n", "The `y` encoding channel sets a mark's vertical position (y-coordinate). Here we've added the `cluster` field using an ordinal (`O`) data type. The result is a discrete axis that includes a sized band, with a default step size, for each unique value:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 192 }, "colab_type": "code", "id": "eP38vNrdNrHF", "outputId": "9ff5b4a8-143c-4595-845f-026ed2e747a8" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point().encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('cluster:O')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "2BQetZgvc0f_" }, "source": [ "_What happens to the chart above if you swap the `O` and `Q` field types?_\n", "\n", "If we instead add the `life_expect` field as a quantitative (`Q`) variable, the result is a scatter plot with linear scales for both axes:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 372 }, "colab_type": "code", "id": "n8PJhH6jN68w", "outputId": "ac41eaeb-4872-48db-ddf1-ab6b5c84f387" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point().encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('life_expect:Q')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "GUKc1DEDTbA0" }, "source": [ "By default, axes for linear quantitative scales include zero to ensure a proper baseline for comparing ratio-valued data. In some cases, however, a zero baseline may be meaningless or you may want to focus on interval comparisons. To disable automatic inclusion of zero, configure the scale mapping using the encoding `scale` attribute:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 372 }, "colab_type": "code", "id": "-6klI5DhSdik", "outputId": "8cb0ca55-176b-4d2f-8891-2c124276e429" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point().encode(\n", " alt.X('fertility:Q', scale=alt.Scale(zero=False)),\n", " alt.Y('life_expect:Q', scale=alt.Scale(zero=False))\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "oUKf6WQmSzqC" }, "source": [ "Now the axis scales no longer include zero by default. Some padding still remains, as the axis domain end points are automatically snapped to _nice_ numbers like multiples of 5 or 10.\n", "\n", "_What happens if you also add `nice=False` to the scale attribute above?_" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "hKCsQ0iIPMTV" }, "source": [ "### Size" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "G7YtT-HNdYT9" }, "source": [ "The `size` encoding channel sets a mark's size or extent. The meaning of the channel can vary based on the mark type. For `point` marks, the `size` channel maps to the pixel area of the plotting symbol, such that the diameter of the point matches the square root of the size value.\n", "\n", "Let's augment our scatter plot by encoding population (`pop`) on the `size` channel. As a result, the chart now also includes a legend for interpreting the size values." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 372 }, "colab_type": "code", "id": "sGENuXRfOIPz", "outputId": "4f76557c-4e35-41fc-9e06-513be34969ae" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point().encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('life_expect:Q'),\n", " alt.Size('pop:Q')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "g5Cu5F2Ad9xG" }, "source": [ "In some cases we might be unsatisfied with the default size range. To provide a customized span of sizes, set the `range` parameter of the `scale` attribute to an array indicating the smallest and largest sizes. Here we update the size encoding to range from 0 pixels (for zero values) to 1,000 pixels (for the maximum value in the scale domain):" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 372 }, "colab_type": "code", "id": "cALgZSQfQzi0", "outputId": "0d88f561-9737-43fa-a84a-7ad6dcdfbf0c" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point().encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('life_expect:Q'),\n", " alt.Size('pop:Q', scale=alt.Scale(range=[0,1000]))\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "yF__0zZ0PJyT" }, "source": [ "### Color and Opacity" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "u5QXPLxJeohH" }, "source": [ "The `color` encoding channel sets a mark's color. The style of color encoding is highly dependent on the data type: nominal data will default to a multi-hued qualitative color scheme, whereas ordinal and quantitative data will use perceptually ordered color gradients.\n", "\n", "Here, we encode the `cluster` field using the `color` channel and a nominal (`N`) data type, resulting in a distinct hue for each cluster value. Can you start to guess what the `cluster` field might indicate?\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 372 }, "colab_type": "code", "id": "bI73XTt5OTmA", "outputId": "f12aeb57-07c5-422e-8cb1-62253b545af8" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point().encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('life_expect:Q'),\n", " alt.Size('pop:Q', scale=alt.Scale(range=[0,1000])),\n", " alt.Color('cluster:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "dNOkUJfNfFac" }, "source": [ "If we prefer filled shapes, we can can pass a `filled=True` parameter to the `mark_point` method:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 372 }, "colab_type": "code", "id": "HH34VMCAQO6s", "outputId": "8aba4f13-bfe3-43b1-e3ea-554a8d20b7f5" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point(filled=True).encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('life_expect:Q'),\n", " alt.Size('pop:Q', scale=alt.Scale(range=[0,1000])),\n", " alt.Color('cluster:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "YY96rt7zfRYG" }, "source": [ "By default, Altair uses a bit of transparency to help combat over-plotting. We are free to further adjust the opacity, either by passing a default value to the `mark_*` method, or using a dedicated encoding channel.\n", "\n", "Here we demonstrate how to provide a constant value to an encoding channel instead of binding a data field:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 372 }, "colab_type": "code", "id": "42kM5nuDOfGm", "outputId": "2dd14842-8fd5-4997-ea47-91cd489e0193" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point(filled=True).encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('life_expect:Q'),\n", " alt.Size('pop:Q', scale=alt.Scale(range=[0,1000])),\n", " alt.Color('cluster:N'),\n", " alt.OpacityValue(0.5)\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "zW2Siu5sPaiE" }, "source": [ "### Shape" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "MGM2hdOqf3Tu" }, "source": [ "The `shape` encoding channel sets the geometric shape used by `point` marks. Unlike the other channels we have seen so far, the `shape` channel can not be used by other mark types. The shape encoding channel should only be used with nominal data, as perceptual rank-order and magnitude comparisons are not supported.\n", "\n", "Let's encode the `cluster` field using `shape` as well as `color`. Using multiple channels for the same underlying data field is known as a *redundant encoding*. The resulting chart combines both color and shape information into a single symbol legend:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 372 }, "colab_type": "code", "id": "czAIeWjSPS5x", "outputId": "e418f006-988c-42a9-9a81-664d1d52d93c" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point(filled=True).encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('life_expect:Q'),\n", " alt.Size('pop:Q', scale=alt.Scale(range=[0,1000])),\n", " alt.Color('cluster:N'),\n", " alt.OpacityValue(0.5),\n", " alt.Shape('cluster:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ramTzfIgUtEi" }, "source": [ "### Tooltips & Ordering" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "VE-29r8dg1Us" }, "source": [ "By this point, you might feel a bit frustrated: we've built up a chart, but we still don't know what countries the visualized points correspond to! Let's add interactive tooltips to enable exploration.\n", "\n", "The `tooltip` encoding channel determines tooltip text to show when a user moves the mouse cursor over a mark. Let's add a tooltip encoding for the `country` field, then investigate which countries are being represented.\n" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 372 }, "colab_type": "code", "id": "61evgaeFUyU0", "outputId": "f13ddd14-3b6f-4f96-ca08-8d3b2ba94a34" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point(filled=True).encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('life_expect:Q'),\n", " alt.Size('pop:Q', scale=alt.Scale(range=[0,1000])),\n", " alt.Color('cluster:N'),\n", " alt.OpacityValue(0.5),\n", " alt.Tooltip('country')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "IRexn5IAhgeW" }, "source": [ "As you mouse around you may notice that you can not select some of the points. For example, the largest dark blue circle corresponds to India, which is drawn on top of a country with a smaller population, preventing the mouse from hovering over that country. To fix this problem, we can use the `order` encoding channel.\n", "\n", "The `order` encoding channel determines the order of data points, affecting both the order in which they are drawn and, for `line` and `area` marks, the order in which they are connected to one another.\n", "\n", "Let's order the values in descending rank order by the population (`pop`), ensuring that smaller circles are drawn later than larger circles:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 372 }, "colab_type": "code", "id": "DywIzwtgVD3Z", "outputId": "3b7254de-09f3-4850-f066-ea8318ec5479" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point(filled=True).encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('life_expect:Q'),\n", " alt.Size('pop:Q', scale=alt.Scale(range=[0,1000])),\n", " alt.Color('cluster:N'),\n", " alt.OpacityValue(0.5),\n", " alt.Tooltip('country:N'),\n", " alt.Order('pop:Q', sort='descending')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Ei93j-daiG6U" }, "source": [ "Now we can identify the smaller country being obscured by India: it's Bangladesh!\n", "\n", "We can also now figure out what the `cluster` field represents. Mouse over the various colored points to formulate your own explanation." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "9bsu1tn_idGt" }, "source": [ "At this point we've added tooltips that show only a single property of the underlying data record. To show multiple values, we can provide the `tooltip` channel an array of encodings, one for each field we want to include:" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 372 }, "colab_type": "code", "id": "450DUk-mXzzQ", "outputId": "ee47eb3b-146d-4c6b-dfa7-94ddeb0fc5d3" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point(filled=True).encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('life_expect:Q'),\n", " alt.Size('pop:Q', scale=alt.Scale(range=[0,1000])),\n", " alt.Color('cluster:N'),\n", " alt.OpacityValue(0.5),\n", " alt.Order('pop:Q', sort='descending'),\n", " tooltip = [\n", " alt.Tooltip('country:N'),\n", " alt.Tooltip('fertility:Q'),\n", " alt.Tooltip('life_expect:Q')\n", " ] \n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "HLQjhEdwiyR2" }, "source": [ "Now we can see multiple data fields upon mouse over!" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "5ViS2LDKRmil" }, "source": [ "### Column and Row Facets" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "apPtlcDoi3yT" }, "source": [ "Spatial position is one of the most powerful and flexible channels for visual encoding, but what can we do if we already have assigned fields to the `x` and `y` channels? One valuable technique is to create a *trellis plot*, consisting of sub-plots that show a subset of the data. A trellis plot is one example of the more general technique of presenting data using [small multiples](https://en.wikipedia.org/wiki/Small_multiple) of views.\n", "\n", "The `column` and `row` encoding channels generate either a horizontal (columns) or vertical (rows) set of sub-plots, in which the data is partitioned according to the provided data field.\n", "\n", "Here is a trellis plot that divides the data into one column per \\`cluster\\` value:" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 441 }, "colab_type": "code", "id": "gszjktorPmRc", "outputId": "b62aff8e-a2aa-409a-be1d-4cf3708f9ab3" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point(filled=True).encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('life_expect:Q'),\n", " alt.Size('pop:Q', scale=alt.Scale(range=[0,1000])),\n", " alt.Color('cluster:N'),\n", " alt.OpacityValue(0.5),\n", " alt.Tooltip('country:N'),\n", " alt.Order('pop:Q', sort='descending'),\n", " alt.Column('cluster:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "8J0dxQoFj9jw" }, "source": [ "The plot above does not fit on screen, making it difficult to compare all the sub-plots to each other! We can set the default `width` and `height` properties to create a smaller set of multiples. Also, as the column headers already label the `cluster` values, let's remove our `color` legend by setting it to `None`. To make better use of space we can also orient our `size` legend to the `'bottom'` of the chart." ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 321 }, "colab_type": "code", "id": "PvKBL59lRrc_", "outputId": "3eb84b63-0c69-4985-ee9b-d0d69e5ffb33" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point(filled=True).encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('life_expect:Q'),\n", " alt.Size('pop:Q', scale=alt.Scale(range=[0,1000]),\n", " legend=alt.Legend(orient='bottom', titleOrient='left')),\n", " alt.Color('cluster:N', legend=None),\n", " alt.OpacityValue(0.5),\n", " alt.Tooltip('country:N'),\n", " alt.Order('pop:Q', sort='descending'),\n", " alt.Column('cluster:N')\n", ").properties(width=135, height=135)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "OmQmca9WkKOU" }, "source": [ "Underneath the hood, the `column` and `row` encodings are translated into a new specification that uses the `facet` view composition operator. We will re-visit faceting in greater depth later on!\n", "\n", "In the meantime, _can you rewrite the chart above to facet into rows instead of columns?_" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "-tZXDmLjbAu5" }, "source": [ "### A Peek Ahead: Interactive Filtering\n", "\n", "In later modules, we'll dive into interaction techniques for data exploration. Here is a sneak peak: binding a range slider to the `year` field to enable interactive scrubbing through each year of data. Don't worry if the code below is a bit confusing at this point, as we will cover interaction in detail later.\n", "\n", "_Drag the slider back and forth to see how the data values change over time!_" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 393 }, "colab_type": "code", "id": "6kQLe1wqZPub", "outputId": "3c934853-9167-4ad1-e560-b366250eb40e" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "select_year = alt.selection_single(\n", " name='select', fields=['year'], init={'year': 1955},\n", " bind=alt.binding_range(min=1955, max=2005, step=5)\n", ")\n", "\n", "alt.Chart(data).mark_point(filled=True).encode(\n", " alt.X('fertility:Q', scale=alt.Scale(domain=[0,9])),\n", " alt.Y('life_expect:Q', scale=alt.Scale(domain=[0,90])),\n", " alt.Size('pop:Q', scale=alt.Scale(domain=[0, 1200000000], range=[0,1000])),\n", " alt.Color('cluster:N', legend=None),\n", " alt.OpacityValue(0.5),\n", " alt.Tooltip('country:N'),\n", " alt.Order('pop:Q', sort='descending')\n", ").add_selection(select_year).transform_filter(select_year)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "UPdDrmm9YK5E" }, "source": [ "## Graphical Marks\n", "\n", "Our exploration of encoding channels above exclusively uses `point` marks to visualize the data. However, the `point` mark type is only one of the many geometric shapes that can be used to visually represent data. Altair includes a number of built-in mark types, including:\n", "\n", "- `mark_area()` - Filled areas defined by a top-line and a baseline.\n", "- `mark_bar()` -\tRectangular bars.\n", "- `mark_circle()`\t- Scatter plot points as filled circles.\n", "- `mark_line()` - Connected line segments.\n", "- `mark_point()` - Scatter plot points with configurable shapes.\n", "- `mark_rect()` - Filled rectangles, useful for heatmaps.\n", "- `mark_rule()` - Vertical or horizontal lines spanning the axis.\n", "- `mark_square()` - Scatter plot points as filled squares.\n", "- `mark_text()` - Scatter plot points represented by text.\n", "- `mark_tick()` - Vertical or horizontal tick marks.\t\n", "\n", "For a complete list, and links to examples, see the [Altair marks documentation](https://altair-viz.github.io/user_guide/marks.html). Next, we will step through a number of the most commonly used mark types for statistical graphics." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "jVp7cC-BbYF5" }, "source": [ "### Point Marks\n", "\n", "The `point` mark type conveys specific points, as in *scatter plots* and *dot plots*. In addition to `x` and `y` encoding channels (to specify 2D point positions), point marks can use `color`, `size`, and `shape` encodings to convey additional data fields.\n", "\n", "Below is a dot plot of `fertility`, with the `cluster` field redundantly encoded using both the `y` and `shape` channels. \n", "\n" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 192 }, "colab_type": "code", "id": "3jrFfaKCtbyL", "outputId": "6332a348-f8f0-4dd8-9c4a-63687e286d4a" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point().encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('cluster:N'),\n", " alt.Shape('cluster:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "bONM4Ccrt4Sw" }, "source": [ "In addition to encoding channels, marks can be stylized by providing values to the `mark_*()` methods.\n", "\n", "For example: point marks are drawn with stroked outlines by default, but can be specified to use `filled` shapes instead. Similarly, you can set a default `size` to set the total pixel area of the point mark.\n" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 192 }, "colab_type": "code", "id": "3-HgJ1PjvKdH", "outputId": "dcf26fa9-281b-4297-da50-84c7f5ccd318" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_point(filled=True, size=100).encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('cluster:N'),\n", " alt.Shape('cluster:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "CGMm4gyNcLzB" }, "source": [ "### Circle Marks\n", "\n", "The `circle` mark type is a convenient shorthand for `point` marks drawn as filled circles." ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 192 }, "colab_type": "code", "id": "R7JgFhB-vn5X", "outputId": "80cd9d0f-c126-4673-bfcf-eaf5b34e0058" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_circle(size=100).encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('cluster:N'),\n", " alt.Shape('cluster:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "IAZSJlWhcOr_" }, "source": [ "### Square Marks\n", "\n", "The `square` mark type is a convenient shorthand for `point` marks drawn as filled squares." ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 192 }, "colab_type": "code", "id": "rfby5R-Mvuwx", "outputId": "8ff4b0d4-f3ce-45e5-f597-1a6fd296ba47" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_square(size=100).encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('cluster:N'),\n", " alt.Shape('cluster:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "SJF0vNqGcRdv" }, "source": [ "### Tick Marks\n", "\n", "The `tick` mark type conveys a data point using a short line segment or \"tick\". These are particularly useful for comparing values along a single dimension with minimal overlap. A *dot plot* drawn with tick marks is sometimes referred to as a *strip plot*." ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 192 }, "colab_type": "code", "id": "Thvp_VJ2v-xd", "outputId": "c6133250-333f-4c29-e217-221634dd8337" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_tick().encode(\n", " alt.X('fertility:Q'),\n", " alt.Y('cluster:N'),\n", " alt.Shape('cluster:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "x8j5XVZJcB7l" }, "source": [ "### Bar Marks\n", "\n", "The \\`bar\\` mark type draws a rectangle with a position, width, and height.\n", "\n", "The plot below is a simple bar chart of the population (\\`pop\\`) of each country." ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 445 }, "colab_type": "code", "id": "eFN9Kw85xFQK", "outputId": "8da431d3-9ba7-4ecf-de55-e478c4527a39" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_bar().encode(\n", " alt.X('country:N'),\n", " alt.Y('pop:Q')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "rHX8bKgbzW3I" }, "source": [ "The bar width is set to a default size. We will discuss how to adjust the bar width later in this notebook. (A subsequent notebook will take a closer look at configuring axes, scales, and legends.)\n", "\n", "Bars can also be stacked. Let's change the `x` encoding to use the `cluster` field, and encode `country` using the `color` channel. We'll also disable the legend (which would be very long with colors for all countries!) and use tooltips for the country name." ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 368 }, "colab_type": "code", "id": "x9maAWhOxsrq", "outputId": "7960be03-eefd-4c3f-a114-8405395c772c" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_bar().encode(\n", " alt.X('cluster:N'),\n", " alt.Y('pop:Q'),\n", " alt.Color('country:N', legend=None),\n", " alt.Tooltip('country:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "de4181jhzgUx" }, "source": [ "In the chart above, the use of the `color` encoding channel causes Altair / Vega-Lite to automatically stack the bar marks. Otherwise, bars would be drawn on top of each other! Try adding the parameter `stack=None` to the `y` encoding channel to see what happens if we don't apply stacking..." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "mLSz2vHb2qiV" }, "source": [ "The examples above create bar charts from a zero-baseline, and the `y` channel only encodes the non-zero value (or height) of the bar. However, the bar mark also allows you to specify starting and ending points to convey ranges.\n", "\n", "The chart below uses the `x` (starting point) and `x2` (ending point) channels to show the range of life expectancies within each regional cluster. Below we use the `min` and `max` aggregation functions to determine the end points of the range; we will discuss aggregation in greater detail in the next notebook!\n", "\n", "Alternatively, you can use `x` and `width` to provide a starting point plus offset, such that `x2 = x + width`." ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 192 }, "colab_type": "code", "id": "NxEVEQLj0l9t", "outputId": "2fa67514-b66c-4449-a1e3-c0b1b377ed3a" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data2000).mark_bar().encode(\n", " alt.X('min(life_expect):Q'),\n", " alt.X2('max(life_expect):Q'),\n", " alt.Y('cluster:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "bTnEQk1NcD7y" }, "source": [ "### Line Marks\n", "\n", "The `line` mark type connects plotted points with line segments, for example so that a line's slope conveys information about the rate of change.\n", "\n", "Let's plot a line chart of fertility per country over the years, using the full, unfiltered global development data frame. We'll again hide the legend and use tooltips instead.\n" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 385 }, "colab_type": "code", "id": "lTWmDwv1Jhzt", "outputId": "7bbd15a9-4b8f-4f66-fe7e-6a55f2c38449" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data).mark_line().encode(\n", " alt.X('year:O'),\n", " alt.Y('fertility:Q'),\n", " alt.Color('country:N', legend=None),\n", " alt.Tooltip('country:N')\n", ").properties(\n", " width=400\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "qmV54UhSMPxU" }, "source": [ "We can see interesting variations per country, but overall trends for lower numbers of children per family over time. Also note that we set a custom width of 400 pixels. _Try changing (or removing) the widths and see what happens!_\n", "\n", "Let's change some of the default mark parameters to customize the plot. We can set the `strokeWidth` to determine the thickness of the lines and the `opacity` to add some transparency. By default, the `line` mark uses straight line segments to connect data points. In some cases we might want to smooth the lines. We can adjust the interpolation used to connect data points by setting the `interpolate` mark parameter. Let's use `'monotone'` interpolation to provide smooth lines that are also guaranteed not to inadvertently generate \"false\" minimum or maximum values as a result of the interpolation." ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 385 }, "colab_type": "code", "id": "PbdSZMs43rgW", "outputId": "07007338-a2c7-4dc2-9f36-bb344e4103ec" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(data).mark_line(\n", " strokeWidth=3,\n", " opacity=0.5,\n", " interpolate='monotone'\n", ").encode(\n", " alt.X('year:O'),\n", " alt.Y('fertility:Q'),\n", " alt.Color('country:N', legend=None),\n", " alt.Tooltip('country:N')\n", ").properties(\n", " width=400\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "_PZcXCF6OZm2" }, "source": [ "The `line` mark can also be used to create *slope graphs*, charts that highlight the change in value between two comparison points using line slopes.\n", "\n", "Below let's create a slope graph comparing the populations of each country at minimum and maximum years in our full dataset: 1955 and 2005. We first create a new Pandas data frame filtered to those years, then use Altair to create the slope graph.\n", "\n", "By default, Altair places the years close together. To better space out the years along the x-axis, we can indicate the size (in pixels) of discrete steps along the width of our chart as indicated by the comment below. Try adjusting the width `step` value below and see how the chart changes in response." ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 385 }, "colab_type": "code", "id": "glipk3XoKUcc", "outputId": "edd1292a-97a7-44d1-b2ec-c5b8d755aa86" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dataTime = data.loc[(data['year'] == 1955) | (data['year'] == 2005)]\n", "\n", "alt.Chart(dataTime).mark_line(opacity=0.5).encode(\n", " alt.X('year:O'),\n", " alt.Y('pop:Q'),\n", " alt.Color('country:N', legend=None),\n", " alt.Tooltip('country:N')\n", ").properties(\n", " width={\"step\": 50} # adjust the step parameter\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "LLo0NmuncGAa" }, "source": [ "### Area Marks\n", "\n", "The `area` mark type combines aspects of `line` and `bar` marks: it visualizes connections (slopes) among data points, but also shows a filled region, with one edge defaulting to a zero-valued baseline." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "mYtoHUPuPpxW" }, "source": [ "The chart below is an area chart of population over time for just the United States:" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 385 }, "colab_type": "code", "id": "cXdOREmBHiaH", "outputId": "37cd899d-2ad1-42ea-fbe0-12e591a28326" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dataUS = data.loc[data['country'] == 'United States']\n", "\n", "alt.Chart(dataUS).mark_area().encode(\n", " alt.X('year:O'),\n", " alt.Y('fertility:Q')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "aDPZ6bWEPv2_" }, "source": [ "Similar to `line` marks, `area` marks support an `interpolate` parameter." ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 385 }, "colab_type": "code", "id": "-ZpfjqMxJvXF", "outputId": "eba5baab-44be-46ac-c9ae-0ad3b094573a" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(dataUS).mark_area(interpolate='monotone').encode(\n", " alt.X('year:O'),\n", " alt.Y('fertility:Q')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "_YolZaDbP7jh" }, "source": [ "Similar to `bar` marks, `area` marks also support stacking. Here we create a new data frame with data for the three North American countries, then plot them using an `area` mark and a `color` encoding channel to stack by country." ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 385 }, "colab_type": "code", "id": "tYOS0Il_H8h3", "outputId": "70e210aa-4771-4ed9-e5a3-0af587d03c60" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dataNA = data.loc[\n", " (data['country'] == 'United States') |\n", " (data['country'] == 'Canada') |\n", " (data['country'] == 'Mexico')\n", "]\n", "\n", "alt.Chart(dataNA).mark_area().encode(\n", " alt.X('year:O'),\n", " alt.Y('pop:Q'),\n", " alt.Color('country:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "oVinPfTZpNtY" }, "source": [ "By default, stacking is performed relative to a zero baseline. However, other `stack` options are available:\n", "\n", "* `center` - to stack relative to a baseline in the center of the chart, creating a *streamgraph* visualization, and\n", "* `normalize` - to normalize the summed data at each stacking point to 100%, enabling percentage comparisons.\n", "\n", "Below we adapt the chart by setting the `y` encoding `stack` attribute to `center`. What happens if you instead set it `normalize`?" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 385 }, "colab_type": "code", "id": "6SQpyJzqpB5G", "outputId": "3a7cb75a-3acf-4b0e-d0e8-cdc7c85fd5ee" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(dataNA).mark_area().encode(\n", " alt.X('year:O'),\n", " alt.Y('pop:Q', stack='center'),\n", " alt.Color('country:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "fQN5a3gfQFBW" }, "source": [ "To disable stacking altogether, set the `stack` attribute to `None`. We can also add `opacity` as a default mark parameter to ensure we see the overlapping areas!" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 385 }, "colab_type": "code", "id": "MY8xDiqkKDMc", "outputId": "41345e53-eeaa-4c69-969d-738c1479ba26" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(dataNA).mark_area(opacity=0.5).encode(\n", " alt.X('year:O'),\n", " alt.Y('pop:Q', stack=None),\n", " alt.Color('country:N')\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ro21p2rsQMl3" }, "source": [ "The `area` mark type also supports data-driven baselines, with both the upper and lower series determined by data fields. As with `bar` marks, we can use the `x` and `x2` (or `y` and `y2`) channels to provide end points for the area mark.\n", "\n", "The chart below visualizes the range of minimum and maximum fertility, per year, for North American countries:" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 385 }, "colab_type": "code", "id": "I084oc4aQeMw", "outputId": "fb6d0868-79f4-4f96-8f5d-aff6d504b3fe" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(dataNA).mark_area().encode(\n", " alt.X('year:O'),\n", " alt.Y('min(fertility):Q'),\n", " alt.Y2('max(fertility):Q')\n", ").properties(\n", " width={\"step\": 40}\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "msL27DW2qoqJ" }, "source": [ "We can see a larger range of values in 1995, from just under 4 to just under 7. By 2005, both the overall fertility values and the variability have declined, centered around 2 children per familty." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "5BoLjQCgrHZL" }, "source": [ "All the `area` mark examples above use a vertically oriented area. However, Altair and Vega-Lite support horizontal areas as well. Let's transpose the chart above, simply by swapping the `x` and `y` channels." ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 506 }, "colab_type": "code", "id": "l_TDR4SNrStr", "outputId": "e7bf35e5-c94b-4316-9f8d-0dc68f242763" }, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "" ], "text/plain": [ "alt.Chart(...)" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alt.Chart(dataNA).mark_area().encode(\n", " alt.Y('year:O'),\n", " alt.X('min(fertility):Q'),\n", " alt.X2('max(fertility):Q')\n", ").properties(\n", " width={\"step\": 40}\n", ")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "OAmIxLRarios" }, "source": [ "## Summary\n", "\n", "We've completed our tour of data types, encoding channels, and graphical marks! You should now be well-equipped to further explore the space of encodings, mark types, and mark parameters. For a comprehensive reference – including features we've skipped over here! – see the Altair [marks](https://altair-viz.github.io/user_guide/marks.html) and [encoding](https://altair-viz.github.io/user_guide/encoding.html) documentation.\n", "\n", "In the next module, we will look at the use of data transformations to create charts that summarize data or visualize new derived fields. In a later module, we'll examine how to further customize your charts by modifying scales, axes, and legends.\n", "\n", "Interested in learning more about visual encoding?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "Bertin's taxonomy of visual encodings from Sémiologie Graphique, as adapted by Mike Bostock." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- The systematic study of marks, visual encodings, and backing data types was initiated by [Jacques Bertin](https://en.wikipedia.org/wiki/Jacques_Bertin) in his pioneering 1967 work [_Sémiologie Graphique (The Semiology of Graphics)_](https://books.google.com/books/about/Semiology_of_Graphics.html?id=X5caQwAACAAJ). The image above illustrates position, size, value (brightness), texture, color (hue), orientation, and shape channels, alongside Bertin's recommendations for the data types they support.\n", "- The framework of data types, marks, and channels also guides _automated_ visualization design tools, starting with [Mackinlay's APT (A Presentation Tool)](https://scholar.google.com/scholar?cluster=10191273548472217907) in 1986 and continuing in more recent systems such as [Voyager](http://idl.cs.washington.edu/papers/voyager/) and [Draco](http://idl.cs.washington.edu/papers/draco/).\n", "- The identification of nominal, ordinal, interval, and ratio types dates at least as far back as S. S. Steven's 1947 article [_On the theory of scales of measurement_](https://scholar.google.com/scholar?cluster=14356809180080326415)." ] } ], "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.7.9" } }, "nbformat": 4, "nbformat_minor": 4 }