Skip to content

Instantly share code, notes, and snippets.

@andyljones
Last active February 13, 2020 17:06
Show Gist options
  • Save andyljones/3b4da7a18d41a8a40f78fbb988bc0548 to your computer and use it in GitHub Desktop.
Save andyljones/3b4da7a18d41a8a40f78fbb988bc0548 to your computer and use it in GitHub Desktop.
Exemplar plot for comparing pairs of discrete distributions
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
def raw_data():
restriction = ['not', 'slightly', 'moderately', 'very']
gov = pd.DataFrame({
'democracy': [.6, .2, .1, .1],
'autocracy': [.2, .3, .5, .4]}, index=restriction)
con = pd.DataFrame({
'uncontentious': [.3, .4, .2, .1],
'contentious': [.1, .2, .3, .4]}, index=restriction)
df = pd.concat({'gov': gov, 'con': con}, 1)
return df
def plot(df):
bottom = df.cumsum() - df
mid = bottom + df/2
colors = plt.cm.inferno(np.linspace(.25, .75, len(restriction)))
colors = dict(zip(restriction, colors))
fig, (left, right) = plt.subplots(1, 2)
fig.set_size_inches(10, 6)
for r in df.index:
left.bar([0, 1], df.gov.loc[r], bottom=bottom.gov.loc[r], color=colors[r], width=.95)
left.annotate(r + '\nrestricted', (0, mid.gov.loc[r].iloc[0]), ha='center', va='center', color='w', size='large')
right.bar([0, 1], df.con.loc[r], bottom=bottom.con.loc[r], color=colors[r], width=.95)
right.annotate(r + '\nrestricted', (0, mid.con.loc[r].iloc[0]), ha='center', va='center', color='w', size='large')
for ax in (left, right):
ax.set_xlim(-.5, +1.5)
ax.set_ylim(0, 1)
ax.set_xticks([0, 1])
ax.set_yticks([])
for s in ax.spines.values():
s.set_visible(False)
ax.xaxis.set_tick_params(length=0, labelsize='large')
ax.xaxis.tick_top()
left.set_xticklabels(df.gov.columns)
right.set_xticklabels(df.con.columns)
df = raw_data()
plot(df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment