Political elections, appointment, analysis and visualization in Python

Overview

rtd ci codecov pyversions pypi pypistatus license coc codestyle colab

Political elections, appointment, analysis and visualization in Python

poli-sci-kit is a Python package for political science appointment and election analysis. The goal is to provide a comprehensive tool for all methods needed to analyze and simulate election results. See the documentation for a full outline of the package including algorithms and visualization techniques.

Contents

Installation

poli-sci-kit can be downloaded from PyPI via pip or sourced directly from this repository:

pip install poli-sci-kit
git clone https://github.com/andrewtavis/poli-sci-kit.git
cd poli-sci-kit
python setup.py install
import poli_sci_kit

Appointment

appointment.methods includes functions to allocate parliamentary seats based on population or vote shares. Included methods are:

Largest Remainder: Hare, Droop, Hagenbach–Bischoff (incl Hamilton, Vinton, Hare–Niemeyer)

Highest Averages: Jefferson, Webster, Huntington-Hill

Arguments to allow allocation thresholds, minimum allocations per group, tie break conditions, and other election features are also provided. Along with deriving results for visualization and reporting, these functions allow the user to analyze outcomes given systematic or situational changes. The appointment.metrics module further provides diagnostics to analyze the results of elections, apportionments, and other political science scenarios.

A basic example of political appointment using poli-sci-kit is:

from poli_sci_kit import appointment

vote_counts = [2700, 900, 3300, 1300, 2150, 500]
seats_to_allocate = 50

# Huntington-Hill is the method used to allocate House of Representatives seats to US states
ha_allocations = appointment.methods.highest_averages(
    averaging_style="Huntington-Hill",
    shares=vote_counts,
    total_alloc=seats_to_allocate,
    alloc_threshold=None,
    min_alloc=1,
    tie_break="majority",
    majority_bonus=False,
    modifier=None,
)

ha_allocations
# [26, 9, 37, 12, 23, 5]

# The Gallagher method is a measure of absolute difference similar to summing square residuals
disproportionality = appointment.metrics.dispr_index(
    shares=vote_counts,
    allocations=ha_allocations,
    metric_type='Gallagher'
)

disproportionality
# 0.01002

We can also check that the allocations pass the quota condition:

passes_qc = appointment.checks.quota_condition(
    shares=vote_counts,
    seats=ha_allocations
)

passes_qc
# True

Allocation consistency can further be checked using dataframes of shares and seats given electoral settings. See appointment.checks and the documentation for explanations of method checks.

Plotting

poli-sci-kit provides Python only implementations of common electoral plots.

Visualizing the above results:

import matplotlib.pyplot as plt
import poli_sci_kit

# German political parties
parties = ['CDU/CSU', 'FDP', 'Greens', 'Die Linke', 'SPD', 'AfD']
party_colors = ['#000000', '#ffed00', '#64a12d', '#be3075', '#eb001f', '#009ee0']

Parliament Plots

poli_sci_kit provides implementations of both rectangular and semicircle parliament plots:

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)

ax1 = poli_sci_kit.plot.parliament(
    allocations=seat_allocations,
    labels=parties,
    colors=party_colors,
    style="rectangle",
    num_rows=4,
    marker_size=300,
    speaker=True,
    axis=ax1,
)

ax2 = poli_sci_kit.plot.parliament(
    allocations=seat_allocations,
    labels=parties,
    colors=party_colors,
    style="semicircle",
    num_rows=4,
    marker_size=175,
    speaker=False,
    axis=ax2,
)

plt.show()

Disproportionality Bar Plot

A novel addition to social science analysis is the disproportionality bar plot, which graphically depicts the disproportionality between expected and realized results. Bar widths are the proportion of shares (ex: votes received), and heights are the difference or relative difference between shares and allocations (ex: parliament seats received).

An example follows:

import pltviz

ax = poli_sci_kit.plot.dispr_bar(
    shares=votes,
    allocations=ha_allocations,
    labels=parties,
    colors=party_colors,
    total_shares=None,
    total_alloc=None,
    percent=True,
    axis=None,
)

handles, labels = pltviz.plot.legend.gen_elements(
    counts=[round(v / sum(votes), 4) for v in votes],
    labels=parties,
    colors=party_colors,
    size=11,
    marker="o",
    padding_indexes=None,
    order=None,
)

ax.legend(
    handles=handles,
    labels=labels,
    title="Vote Percents (bar widths)",
    title_fontsize=15,
    fontsize=11,
    ncol=2,
    loc="upper left",
    bbox_to_anchor=(0, 1),
    frameon=True,
    facecolor="#FFFFFF",
    framealpha=1,
)

ax.axes.set_title('Seat to Vote Share Disproportionality', fontsize=30)
ax.set_xlabel('Parties', fontsize=20)
ax.set_ylabel('Percent Shift', fontsize=20)

plt.show()

Examples

Examples in poli-sci-kit use publicly available Wikidata statistics sourced via the Python package wikirepo. Current examples include:

  • US HoR

    • Allocates seats to a version of the US House of Representatives that includes all US territories and Washington DC given census data, with this further being used to derive relative vote strengths of state citizens in the US presidential election
  • Global Parliament

    • Analyzes the allocation of seats in a hypothetical global parliament given the prevalence of certain countries and organizations, the distribution of seats based on Freedom House indexes, as well as disproportionality metrics

To-Do

Please see the contribution guidelines if you are interested in contributing to this project. Work that is in progress or could be implemented includes:

References

Full list of references

Comments
  • Add equations to appointment.methods docstrings

    Add equations to appointment.methods docstrings

    Equations should be added to the doc strings of largest_remainder and highest_average in poli_sci_kit.appointment.methods. They would then be rendered in the documentation for greater clarity.

    Most of these equations can be found on the Wikipedia pages for the respective methods. They should be placed in the options section of the quota_style and averaging_style parameters respectively.

    documentation help wanted good first issue 
    opened by andrewtavis 6
  • Bump urllib3 from 1.26.3 to 1.26.4

    Bump urllib3 from 1.26.3 to 1.26.4

    ⚠️ Dependabot is rebasing this PR ⚠️

    If you make any changes to it yourself then they will take precedence over the rebase.


    Bumps urllib3 from 1.26.3 to 1.26.4.

    Release notes

    Sourced from urllib3's releases.

    1.26.4

    :warning: IMPORTANT: urllib3 v2.0 will drop support for Python 2: Read more in the v2.0 Roadmap

    • Changed behavior of the default SSLContext when connecting to HTTPS proxy during HTTPS requests. The default SSLContext now sets check_hostname=True.

    If you or your organization rely on urllib3 consider supporting us via GitHub Sponsors

    Changelog

    Sourced from urllib3's changelog.

    1.26.4 (2021-03-15)

    • Changed behavior of the default SSLContext when connecting to HTTPS proxy during HTTPS requests. The default SSLContext now sets check_hostname=True.
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 2
  • [ImgBot] Optimize images

    [ImgBot] Optimize images

    Beep boop. Your images are optimized!

    Your image file size has been reduced by 41% 🎉

    Details

    | File | Before | After | Percent reduction | |:--|:--|:--|:--| | /resources/gh_images/semicircle_parliament.png | 81.86kb | 18.55kb | 77.34% | | /resources/gh_images/rectangle_parliament.png | 9.29kb | 3.47kb | 62.65% | | /resources/poli-sci-kit_logo_transparent.png | 152.83kb | 95.31kb | 37.63% | | /resources/poli-sci-kit_logo.png | 139.30kb | 90.68kb | 34.91% | | /resources/gh_images/dispr_bar.png | 103.09kb | 77.35kb | 24.97% | | | | | | | Total : | 486.37kb | 285.36kb | 41.33% |


    Black Lives Matter | 💰 donate | 🎓 learn | ✍🏾 sign

    📝 docs | :octocat: repo | 🙋🏾 issues | 🏅 swag | 🏪 marketplace

    opened by imgbot[bot] 1
  • Bump cryptography from 3.3.1 to 3.3.2

    Bump cryptography from 3.3.1 to 3.3.2

    Bumps cryptography from 3.3.1 to 3.3.2.

    Changelog

    Sourced from cryptography's changelog.

    3.3.2 - 2021-02-07

    
    * **SECURITY ISSUE:** Fixed a bug where certain sequences of ``update()`` calls
      when symmetrically encrypting very large payloads (>2GB) could result in an
      integer overflow, leading to buffer overflows. *CVE-2020-36242*
    

    .. _v3-3-1:

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
  • Create concise requirement and env files

    Create concise requirement and env files

    This issue is for creating concise versions of requirements.txt and environment.yml for poli-sci-kit. It would be great if these files were created by hand with specific version numbers or generated in a way so that sub-dependencies don't always need to be updated.

    As of now both files are being created with the following commands in the package's conda virtual environment:

    pip list --format=freeze > requirements.txt  
    conda env export --no-builds | grep -v "^prefix: " > environment.yml
    

    poli-sci-kit and other obviously unneeded packages are then removed from these files before being uploaded.

    Any insights or help would be much appreciated!

    help wanted good first issue question 
    opened by andrewtavis 0
  • Add equations to appointment.metrics docstrings

    Add equations to appointment.metrics docstrings

    This issue is for adding LaTeX equations to the docstrings of all functions found in poli_sci_kit.appointment.metrics. The style should be similar to those found in poli_sci_kit.appointment.methods.

    The following is an explanation for how to write LaTeX in docstrings:

    1. In conf.py of the documentation you need the extension sphinx.ext.imgmath, which allows equations to be rendered to pngs (this has been added to poli-sci-kit's conf.py)
    2. If you want to add an equation, then as seen in the docstrings for appointment.methods you add the following:
    .. math::
        LaTeX you want rendered
    
    1. The docstring also needs to be converted to an r-sting (this is now the case for largest_remainder and highest_averages)
    2. You also need to use &= instead of = in equations

    This LaTeX editor could be used to test equations and then add them to the docstrings (remembering &= instead of =). I would be more than happy to help if one of the equations doesn't make sense, or if getting the LaTeX to work is a bit confusing :)

    Thanks for your interest in contributing!

    documentation help wanted good first issue 
    opened by andrewtavis 0
  • New appointment arguments

    New appointment arguments

    Please use this issue to suggest new arguments for poli-sci-kit.appointment.methods functions if you know of a style of appointment variable that is not yet implemented. These new arguments can then be converted into good first issues that would include the necessary codes for implementation and testing.

    Thanks for your interest in contributing!

    enhancement help wanted question 
    opened by andrewtavis 0
  • Add Adams method to appointment.methods.highest_averages

    Add Adams method to appointment.methods.highest_averages

    The Adams method, as described on Wikipedia, is another highest averages method that could be implemented. This method has been implemented in voting, but lacks the allocation conditions that poli-sci-kit provide.

    This issue would be to add this method to appointment.methods.highest_averages in a way that allows for minimum allocations, tie break conditions, majority bonus rules, and other conditional rulesets.

    enhancement help wanted good first issue 
    opened by andrewtavis 0
  • Accurate semicircle parliament plot allocations

    Accurate semicircle parliament plot allocations

    The semicircle version of the parliament plot at times doesn't put all the seats for a group in the same area. There is potentially a better method of allocating the scatterplot points in that function, or break points could be put in given parliament sizes to assure that groups have all their seats in one area of the plot.

    Fixes for this would specifically need to target poli_sci_kit.utils.gen_parl_points.

    enhancement help wanted 
    opened by andrewtavis 0
Releases(v1.0.0)
  • v1.0.0(Dec 28, 2021)

  • v0.1.2.5(Mar 24, 2021)

    Changes include:

    • Package structure has been modified for better testing and a cleaner wheel

    • Bug fixes and refactoring for cleaner code

    • Checks for code quality have been added

    • Examples now function in Google Colab

    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Feb 10, 2021)

    First stable release of poli-sci-kit

    Changes include:

    • Plotting functions for parliament allocations and seat disproportionality

    • Full documentation of the package

    • Virtual environment files

    • Bug fixes

    • Extensive testing of all modules with GH Actions and Codecov

    • Code of conduct and contribution guidelines

    Source code(tar.gz)
    Source code(zip)
  • v0.0.2.1(Dec 9, 2020)

    The minimum viable product of poli-sci-kit

    • Users are able to do political appointments using a variety of methods including largest remainder and highest average techniques

    • Users are able to analyze the results of appointments

    • Usage examples have been created

    Source code(tar.gz)
    Source code(zip)
Owner
Andrew Tavis McAllister
Data scientist, developer and designer. Humboldt University of Berlin (MS); University of Oregon (BA).
Andrew Tavis McAllister
HW 2: Visualizing interesting datasets

HW 2: Visualizing interesting datasets Check out the project instructions here! Mean Earnings per Hour for Males and Females My first graph uses data

7 Oct 27, 2021
An interactive dashboard built with python that enables you to visualise how rent prices differ across Sweden.

sweden-rent-dashboard An interactive dashboard built with python that enables you to visualise how rent prices differ across Sweden. The dashboard/web

Rory Crean 5 Dec 19, 2021
MPL Plotter is a Matplotlib based Python plotting library built with the goal of delivering publication-quality plots concisely.

MPL Plotter is a Matplotlib based Python plotting library built with the goal of delivering publication-quality plots concisely.

Antonio López Rivera 162 Nov 11, 2022
Python & Julia port of codes in excellent R books

X4DS This repo is a collection of Python & Julia port of codes in the following excellent R books: An Introduction to Statistical Learning (ISLR) Stat

Gitony 5 Jun 21, 2022
Visualization Library

CamViz Overview // Installation // Demos // License Overview CamViz is a visualization library developed by the TRI-ML team with the goal of providing

Toyota Research Institute - Machine Learning 67 Nov 24, 2022
Jupyter Notebook extension leveraging pandas DataFrames by integrating DataTables and ChartJS.

Jupyter DataTables Jupyter Notebook extension to leverage pandas DataFrames by integrating DataTables JS. About Data scientists and in fact many devel

Marek Čermák 142 Dec 28, 2022
Statistics and Visualization of acceptance rate, main keyword of CVPR 2021 accepted papers for the main Computer Vision conference (CVPR)

Statistics and Visualization of acceptance rate, main keyword of CVPR 2021 accepted papers for the main Computer Vision conference (CVPR)

Hoseong Lee 78 Aug 23, 2022
Param: Make your Python code clearer and more reliable by declaring Parameters

Param Param is a library providing Parameters: Python attributes extended to have features such as type and range checking, dynamically generated valu

HoloViz 304 Jan 07, 2023
Fractals plotted on MatPlotLib in Python.

About The Project Learning more about fractals through the process of visualization. Built With Matplotlib Numpy License This project is licensed unde

Akeel Ather Medina 2 Aug 30, 2022
Getting started with Python, Dash and Plot.ly for the Data Dashboards team

data_dashboards Getting started with Python, Dash and Plot.ly for the Data Dashboards team Getting started MacOS users: # Install the pyenv version ma

Department for Levelling Up, Housing and Communities 1 Nov 08, 2021
Statistical data visualization using matplotlib

seaborn: statistical data visualization Seaborn is a Python visualization library based on matplotlib. It provides a high-level interface for drawing

Michael Waskom 10.2k Dec 30, 2022
Lumen provides a framework for visual analytics, which allows users to build data-driven dashboards from a simple yaml specification

Lumen project provides a framework for visual analytics, which allows users to build data-driven dashboards from a simple yaml specification

HoloViz 120 Jan 04, 2023
LabGraph is a a Python-first framework used to build sophisticated research systems with real-time streaming, graph API, and parallelism.

LabGraph is a a Python-first framework used to build sophisticated research systems with real-time streaming, graph API, and parallelism.

MLH Fellowship 7 Oct 05, 2022
🎨 Python3 binding for `@AntV/G2Plot` Plotting Library .

PyG2Plot 🎨 Python3 binding for @AntV/G2Plot which an interactive and responsive charting library. Based on the grammar of graphics, you can easily ma

hustcc 990 Jan 05, 2023
Streamlit component for Let's-Plot visualization library

streamlit-letsplot This is a work-in-progress, providing a convenience function to plot charts from the Lets-Plot visualization library. Example usage

Randy Zwitch 9 Nov 03, 2022
Visualise Ansible execution time across playbooks, tasks, and hosts.

ansible-trace Visualise where time is spent in your Ansible playbooks: what tasks, and what hosts, so you can find where to optimise and decrease play

Mark Hansen 81 Dec 15, 2022
阴阳师后台全平台(使用网易 MuMu 模拟器)辅助。支持御魂,觉醒,御灵,结界突破,秘闻副本,地域鬼王。

阴阳师后台全平台辅助 Python 版本:Python 3.8.3 模拟器:网易 MuMu | 雷电模拟器 模拟器分辨率:1024*576 显卡渲染模式:兼容(OpenGL) 兼容 Windows 系统和 MacOS 系统 思路: 利用 adb 截图后,使用 opencv 找图找色,模拟点击。使用

简讯 27 Jul 09, 2022
Plot-configurations for scientific publications, purely based on matplotlib

TUEplots Plot-configurations for scientific publications, purely based on matplotlib. Usage Please have a look at the examples in the example/ directo

Nicholas Krämer 487 Jan 08, 2023
Material for dataviz course at university of Bordeaux

Material for dataviz course at university of Bordeaux

Nicolas P. Rougier 50 Jul 17, 2022
Create a visualization for Trump's Tweeted Words Using Python

Data Trump's Tweeted Words This plot illustrates twitter word occurences. We already did the coding I needed for this plot, so I was very inspired to

7 Mar 27, 2022