{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Political Alignment and Other Views" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Introduction\n", "\n", "This is the fourth in a series of notebooks that make up a [case study in exploratory data analysis](https://allendowney.github.io/PoliticalAlignmentCaseStudy/).\n", "This case study is part of the [*Elements of Data Science*](https://allendowney.github.io/ElementsOfDataScience/) curriculum.\n", "\n", "This notebook is a template for a do-it-yourself, choose-your-own-adventure mini-project that explores the relationship between political alignment and other attitudes and beliefs.\n", "\n", "I will outline the steps and provide sample code. You can choose which survey question to explore, adapt my code for your data, and write a report presenting the results.\n", "\n", "As an example, I wrote up [the results from this notebook in a blog article](https://www.allendowney.com/blog/2019/12/03/political-alignment-and-beliefs-about-homosexuality/)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In previous notebooks, we looked at changes in political alignment over time, and explored the relationship between political alignment and survey questions related to \"outlook\".\n", "\n", "The analysis in this notebook follows the steps we have seen:\n", "\n", "1) For your variable of interest, you will read the code book to understand the question and valid responses.\n", "\n", "2) You will compute and display the distribution (PMF) of responses and the distribution within each political group.\n", "\n", "3) You will recode the variable on a numerical scale that makes it possible to interpret the mean, and then plot the mean over time.\n", "\n", "4) You will use a pivot table to compute the mean of your variable over time for each political alignment group (liberal, moderate, and conservative).\n", "\n", "5) Finally, you will look at results from three resamplings of the data to see whether the patterns you observed might be due to random sampling." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following cell installs the `empiricaldist` library if necessary." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "try:\n", " import empiricaldist\n", "except ImportError:\n", " !pip install empiricaldist" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If everything we need is installed, the following cell should run without error." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "\n", "from empiricaldist import Pmf" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following cells define functions from previous notebooks we will use again." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "def decorate(**options):\n", " \"\"\"Decorate the current axes.\n", " Call decorate with keyword arguments like\n", " decorate(title='Title',\n", " xlabel='x',\n", " ylabel='y')\n", " The keyword arguments can be any of the axis properties\n", " https://matplotlib.org/api/axes_api.html\n", " \"\"\"\n", " ax = plt.gca()\n", " ax.set(**options)\n", " handles, labels = ax.get_legend_handles_labels()\n", " if handles:\n", " plt.legend()\n", " plt.tight_layout()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "from statsmodels.nonparametric.smoothers_lowess import lowess\n", "\n", "def make_lowess(series):\n", " \"\"\"Use LOWESS to compute a smooth line.\n", " \n", " series: pd.Series\n", " \n", " returns: pd.Series\n", " \"\"\"\n", " y = series.values\n", " x = series.index.values\n", "\n", " smooth = lowess(y, x)\n", " index, data = np.transpose(smooth)\n", "\n", " return pd.Series(data, index=index) " ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "def plot_series_lowess(series, color):\n", " \"\"\"Plots a series of data points and a smooth line.\n", " \n", " series: pd.Series\n", " color: string or tuple\n", " \"\"\"\n", " series.plot(linewidth=0, marker='o', color=color, alpha=0.5)\n", " smooth = make_lowess(series)\n", " smooth.plot(label='_', color=color)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def plot_columns_lowess(table, columns, color_map):\n", " \"\"\"Plot the columns in a DataFrame.\n", " \n", " table: DataFrame with a cross tabulation\n", " columns: list of column names, in the desired order\n", " color_map: mapping from column names to color_map\n", " \"\"\"\n", " for col in columns:\n", " series = table[col]\n", " plot_series_lowess(series, color_map[col])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Loading the data\n", "\n", "In the first notebook, we downloaded GSS data, loaded and cleaned it, resampled it to correct for stratified sampling, and then saved the data in an HDF5 file, which is much faster to load.\n", "\n", "The following cells downloads the file." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "from os.path import basename, exists\n", "\n", "def download(url):\n", " filename = basename(url)\n", " if not exists(filename):\n", " from urllib.request import urlretrieve\n", " local, _ = urlretrieve(url, filename)\n", " print('Downloaded ' + local)\n", "\n", "download('https://github.com/AllenDowney/PoliticalAlignmentCaseStudy/' +\n", " 'raw/update2021/gss_eds.3.hdf5')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now I'll load the first resampled `DataFrame`." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "datafile = 'gss_eds.3.hdf5'\n", "gss = pd.read_hdf(datafile, 'gss0')\n", "gss.shape" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 10, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 11, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Changes in social attitudes\n", "\n", "The General Social Survey includes questions about a variety of social attitudes and beliefs. We can use this dataset to explore changes in the responses over time and the relationship with political alignment.\n", "\n", "In my subset of the GSS data, I selected questions that were asked repeatedly over the interval of the survey.\n", "\n", "To follow the process demonstrated in this notebook, you should choose a variable that you think might be interesting.\n", "\n", "If you are not sure which variable to explore, here is a [random selection of three that you can choose from](https://en.wikipedia.org/wiki/The_Paradox_of_Choice):" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "cols = list(gss.columns)\n", "for col in ['id_', 'year', 'ballot', 'age', 'sex', 'race']:\n", " cols.remove(col)\n", " \n", "np.random.shuffle(cols)\n", "for col in cols[:3]:\n", " print(col)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Fill in the name of the variable you chose below, and select a column." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Responses\n", "\n", "Here's the distribution of responses:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Use this link to read the codebook](https://gss.norc.org/Documents/codebook/GSS%202021%20Codebook%20R1.pdf) for the variable you chose.\n", "\n", "Then fill in the following cell with the responses and their labels." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "responses = [1, 2, 3, 4, 5]\n", "\n", "labels = ['Always wrong',\n", " 'Almost always wrong',\n", " 'Sometimes wrong',\n", " 'Not at all wrong',\n", " 'Other']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And here's what the distribution looks like." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "pmf = Pmf.from_seq(column)\n", "pmf.bar(alpha=0.7)\n", "\n", "decorate(xlabel='Response',\n", " ylabel='PMF',\n", " title='Distribution of responses')\n", "\n", "plt.xticks(responses, labels, rotation=30);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Remember that these results are an average over the entire interval of the survey, so you should not interpret it as a current condition." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Responses over time\n", "\n", "If we make a cross tabulation of `year` and the variable of interest, we get the distribution of responses over time." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 18, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 19, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can plot the results." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "for response, label in zip(responses, labels):\n", " xtab[response].plot(label=label)\n", "\n", "decorate(xlabel='Year',\n", " ylabel='Percentage',\n", " title='Attitudes about same-sex relations')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This visualization is useful for exploring the data, but I would not present this version to an audience." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Political alignment\n", "\n", "To explore the relationship between this variable and political alignment, I'll recode political alignment into three groups:" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "d_polviews = {1: 'Liberal', \n", " 2: 'Liberal', \n", " 3: 'Liberal', \n", " 4: 'Moderate', \n", " 5: 'Conservative', \n", " 6: 'Conservative', \n", " 7: 'Conservative'}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "I'll use `replace` and store the result as a new column in the DataFrame." ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "gss['polviews3'] = gss['polviews'].replace(d_polviews)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With this scale, there are roughly the same number of people in each group." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "gss['polviews3'].value_counts(dropna=False)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "pmf = Pmf.from_seq(gss['polviews3'])\n", "pmf.bar(color='C1', alpha=0.7)\n", "\n", "decorate(xlabel='Political alignment',\n", " ylabel='PMF',\n", " title='Distribution of political alignment')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Group by political alignment\n", "\n", "Now we can use `groupby` to group the respondents by political alignment." ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next I will plot the distribution of responses in each group.\n", "\n", "But first I'll make a dictionary that maps from each group to a color." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "muted = sns.color_palette('muted', 5)\n", "sns.palplot(muted)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "color_map = {'Conservative': muted[3], \n", " 'Moderate': muted[4], \n", " 'Liberal': muted[0]}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now I'll make a PMF of responses for each group." ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "for name, group in by_polviews:\n", " plt.figure()\n", " pmf = Pmf.from_seq(group[varname])\n", " pmf.bar(label=name, color=color_map[name], alpha=0.7)\n", " \n", " decorate(xlabel='Response',\n", " ylabel='PMF',\n", " title='Distribution of responses')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But again, these results are an average over the interval of the survey, so you should not interpret them as a current condition." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Recode\n", "\n", "For each group, we could compute the mean of the responses, but it would be hard to interpret. So we'll recode the variable of interest to make the mean more... meaningful.\n", "\n", "For the variable I chose, a majority of respondents chose \"always wrong\". I'll use that as my baseline response with code 1, and lump the other responses with code 0.\n", "\n", "We can use `replace` to recode the values and store the result as a new column in the DataFrame." ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And we'll use `value_counts` to check whether it worked." ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "gss['recoded'].value_counts(dropna=False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we compute the mean, we can interpret it as \"the fraction of respondents who think same-sex sexual relations are always wrong\".\n", "\n", "NOTE: `Series.mean` drops NaN values before computing the mean." ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Average by group\n", "\n", "\n", "\n", "Now we can compute the mean of the recoded variable in each group." ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To get the values in a particular order, we can use the group names as an index:" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "names = ['Conservative', 'Moderate', 'Liberal']\n", "means[names]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can make a bar plot with color-coded bars:" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "colors = color_map.values()\n", "\n", "means[names].plot(kind='bar', color=colors, alpha=0.7)\n", "\n", "decorate(xlabel='Political alignment',\n", " ylabel='Fraction saying yes',\n", " title='Are same-sex sexual relations always wrong?')\n", "\n", "plt.xticks(rotation=0);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As we might expect, more conservatives think homosexuality is \"always wrong\", compared to moderates and liberals." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Time series\n", "\n", "We can use `groupby` to group responses by year." ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "From the result we can select the recoded variable and compute the mean." ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And we can plot the results with the data points themselves as circles and a local regression model as a line." ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "plot_series_lowess(time_series, 'C1')\n", "\n", "decorate(xlabel='Year',\n", " ylabel='Fraction saying yes',\n", " title='Are same-sex sexual relations always wrong?')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The fraction of respondents who think homosexuality is wrong has been falling steeply since about 1990." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Time series by group\n", "\n", "So far, we have grouped by `polviews3` and computed the mean of the variable of interest in each group.\n", "\n", "Then we grouped by `year` and computed the mean for each year.\n", "\n", "Now we'll use `pivot_table` to compute the mean in each group for each year." ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 39, "metadata": { "tags": [] }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result is a table that has years running down the rows and political alignment running across the columns.\n", "\n", "Each entry in the table is the mean of the variable of interest for a given group in a given year." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Plotting the results\n", "\n", "Now we can use `plot_columns_lowess` to see the results." ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [ "columns = ['Conservative', 'Moderate', 'Liberal']\n", "plot_columns_lowess(table, columns, color_map)\n", "\n", "decorate(xlabel='Year',\n", " ylabel='Fraction saying yes',\n", " title='Are same-sex sexual relations always wrong?')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Negative attitudes about homosexuality have been declining in all three groups, starting at about the same time, and at almost the same rate." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Resampling\n", "\n", "The figures we have generated so far in this notebook are based on a single resampling of the GSS data. Some of the features we see in these figures might be due to random sampling rather than actual changes in the world.\n", "\n", "By generating the same figures with different resampled datasets, we can get a sense of how much variation there is due to random sampling.\n", "\n", "To make that easier, the following function contains the code from the previous analysis all in one place.\n", "\n", "You will probably have to update this function with any changes you made in my code." ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "def plot_by_polviews(gss, varname):\n", " \"\"\"Plot mean response by polviews and year.\n", " \n", " gss: DataFrame\n", " varname: string column name\n", " \"\"\"\n", " gss['polviews3'] = gss['polviews'].replace(d_polviews)\n", " \n", " column = gss[varname]\n", " gss['recoded'] = column.replace(d_recode)\n", " \n", " table = gss.pivot_table(values='recoded', \n", " index='year', \n", " columns='polviews3', \n", " aggfunc='mean')\n", "\n", " columns = ['Conservative', 'Moderate', 'Liberal']\n", " plot_columns_lowess(table, columns, color_map)\n", "\n", " decorate(xlabel='Year',\n", " ylabel='Fraction saying yes',\n", " title='Are same-sex relations always wrong?')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can loop through the three resampled datasets and generate a figure for each one." ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "for key in ['gss0', 'gss1', 'gss2']:\n", " df = pd.read_hdf('gss_eds.3.hdf5', key)\n", "\n", " plt.figure()\n", " plot_by_polviews(df, varname)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You should review your interpretation in the previous section to see how it holds up to resampling. If you see an effect that is consistent in all three figures, it is less likely to be an artifact of random sampling.\n", "\n", "If it varies from one resampling to the next, you should probably not take it too seriously." ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "Political Alignment Case Study\n", "\n", "Copyright 2020 Allen B. Downey\n", "\n", "License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], "metadata": { "celltoolbar": "Tags", "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.10" } }, "nbformat": 4, "nbformat_minor": 4 }