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/rol_panel.csv')
d=p[p.year>=2010].groupby('code').agg(rle=('rle','mean'),polyarchy=('polyarchy','mean'),gdppc=('gdppc','mean')).dropna()

fig,ax=plt.subplots(figsize=(7.2,5.0))
# fit line
import numpy as np
b,a=np.polyfit(d.polyarchy,d.rle,1)
xs=np.linspace(0,1,50)
ax.plot(xs,a+b*xs,color='#888',lw=1.2,ls='--',zorder=1,label='Overall fit')
ax.scatter(d.polyarchy,d.rle,s=18,color='#9bb8d3',edgecolor='#5f7d99',lw=0.4,zorder=2)

highlight={'SGP':'Singapore','HKG':'Hong Kong','QAT':'Qatar','OMN':'Oman','ARE':'UAE','MYS':'Malaysia'}
for c,nm in highlight.items():
    if c in d.index:
        x,y=d.loc[c,'polyarchy'],d.loc[c,'rle']
        ax.scatter([x],[y],s=46,color='#c0504d',edgecolor='#7a2d2b',lw=0.6,zorder=4)
        ax.annotate(nm,(x,y),xytext=(6,3),textcoords='offset points',fontsize=8.5,color='#7a2d2b')

ax.axhline(0,color='#ccc',lw=0.6,zorder=0)
ax.set_xlabel('Electoral democracy (V-Dem polyarchy, 0 to 1)',fontsize=10)
ax.set_ylabel('Rule of law (World Bank WGI estimate)',fontsize=10)
ax.set_title('The rule of law does not require the ballot',fontsize=12.5,pad=10)
ax.text(0.02,0.97,'Highlighted states rank high on the rule of law\nwhile holding little electoral democracy.',
        transform=ax.transAxes,va='top',ha='left',fontsize=8.5,color='#555')
ax.set_xlim(-0.02,1.02); 
for s in ['top','right']: ax.spines[s].set_visible(False)
plt.tight_layout()
plt.savefig('/tmp/fig_rule_of_law.png',dpi=170)
print("saved fig_rule_of_law.png")
