import pandas as pd, numpy as np
import matplotlib; matplotlib.use('Agg'); import matplotlib.pyplot as plt
plt.rcParams['font.family']='DejaVu Serif'
p=pd.read_csv('/tmp/glob_panel.csv')
nd=p.dropna(subset=['poly']); nd=nd[nd.poly<0.5]
# collapse to country means for a clean cross-section
g=nd.groupby('code').agg(cc=('cc','mean'),trade=('trade','mean')).dropna()
g=g[g.trade<200]  # drop a couple of extreme entrepots for readability
fig,ax=plt.subplots(figsize=(7.0,4.8))
b,a=np.polyfit(g.trade,g.cc,1); xs=np.linspace(g.trade.min(),g.trade.max(),50)
ax.plot(xs,a+b*xs,color='#c0504d',lw=1.6,zorder=3,label='Fit')
ax.scatter(g.trade,g.cc,s=22,color='#9bb8d3',edgecolor='#5f7d99',lw=0.4,zorder=2)
ax.axhline(0,color='#ccc',lw=0.6)
ax.set_xlabel('Trade openness (exports + imports, % of GDP)',fontsize=10)
ax.set_ylabel('Control of corruption (World Bank WGI)',fontsize=10)
ax.set_title('Among non-democracies, the more connected, the cleaner the state',fontsize=12,pad=10)
for s in ['top','right']: ax.spines[s].set_visible(False)
plt.tight_layout(); plt.savefig('/tmp/fig_connected_governance.png',dpi=170)
print("saved; n_countries=%d slope=%.4f"%(len(g),b))
