text_html_output_1.png
from matplotlib.lines import Line2D

import pandas as pd

import statsmodels.formula.api as smf

url = 'https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/swiss.csv'
df = pd.read_csv(url, index_col=0)

df.columns = ['fertility', 'agri', 'exam', 'edu', 'catholic', 'infant_mort']

formula = 'fertility ~ %s' % ' + '.join(df.columns.values[1:])
formula

lin_reg = smf.ols(formula, data=df).fit()
lin_reg.summary()

err_series = lin_reg.params - lin_reg.conf_int()[0]
err_series

coef_df = pd.DataFrame({'coef': lin_reg.params.values[1:], 'err': err_series.values[1:], 'varname': err_series.index.values[1:]})
coef_df

formula_1 = 'fertility ~ %s' % ' + '.join(df.columns.values[1:-1])
mod_1 = smf.ols(formula_1, data=df).fit()
mod_1.params

formula_2 = 'fertility ~ %s' % ' + '.join(df.columns.values[1:-2].tolist() + ['infant_mort'])
mod_2 = smf.ols(formula_2, data=df).fit()
mod_2.params

coef_df = pd.DataFrame()
for i, mod in enumerate([mod_1, mod_2]):
    err_series = mod.params - mod.conf_int()[0]
    coef_df = coef_df.append(pd.DataFrame({'coef': mod.params.values[1:], 'err': err_series.values[1:], 'varname': err_series.index.values[1:], 'model': 'model %d' % (i + 1)}))
coef_df

marker_list = 'so'
width = 0.25
base_x = pd.np.arange(5) - 0.2
base_x

fig, ax = plt.subplots(figsize=(8, 5))
for i, mod in enumerate(coef_df.model.unique()):
    mod_df = coef_df[coef_df.model == mod]
    mod_df = mod_df.set_index('varname').reindex(coef_df['varname'].unique())
    X = base_x + width * i
    ax.bar(X, mod_df['coef'], color='none', yerr=mod_df['err'])
    ax.set_ylabel('')
    ax.set_xlabel('')
    ax.scatter(x=X, marker=marker_list[i], s=120, y=mod_df['coef'], color='black')
    ax.axhline(y=0, linestyle='--', color='black', linewidth=4)
    ax.xaxis.set_ticks_position('none')
    _ = ax.set_xticklabels(['', 'Agriculture', 'Exam', 'Edu.', 'Catholic', 'Infant Mort.'], rotation=0, fontsize=16)
    fs = 16
    ax.annotate('Control', xy=(0.3, -0.2), xytext=(0.3, -0.35), xycoords='axes fraction', textcoords='axes fraction', fontsize=fs, ha='center', va='bottom', bbox=dict(boxstyle='square', fc='white', ec='black'), arrowprops=dict(arrowstyle='-[, widthB=6.5, lengthB=1.2', lw=2.0, color='black'))
    ax.annotate('Study', xy=(0.8, -0.2), xytext=(0.8, -0.35), xycoords='axes fraction', textcoords='axes fraction', fontsize=fs, ha='center', va='bottom', bbox=dict(boxstyle='square', fc='white', ec='black'), arrowprops=dict(arrowstyle='-[, widthB=3.5, lengthB=1.2', lw=2.0, color='black'))
legend_elements = [Line2D([0], [0], marker=m, label='Model %d' % i, color='k', markersize=10) for i, m in enumerate(marker_list)]
_ = ax.legend(handles=legend_elements, loc=2, prop={'size': 15}, labelspacing=1.2)