Showing posts with label kountry. Show all posts
Showing posts with label kountry. Show all posts

Apr 19, 2018

Random graphs (131): Scatterplot

sdmxuse data ESTAT, clear dataset(crim_pris_cap) dimensions(A.PRIS_ACT_CAP.P_HTHAB.)
drop unit indic_cr freq 
rename value prison
tempfile x
replace geo = "UK" if geo == "UKC-L"
save `x', replace

sdmxuse data ESTAT, clear dataset(spr_exp_sum) start(2008) end(2015) dimensions(A.TOTALNOREROUTE.PC_GDP..)
drop spdeps unit freq
rename value spending

merge 1:1 geo time using `x', keep(match) nogenerate
replace geo = "GR" if geo == "EL"

kountry geo, from(iso2c)
rename NAMES_STD country

regress prison spending if time == "2015"
local r2 = round(`e(r2)', .01) * 100
twoway (scatter prison spending if time == "2015", mlabel(country)) ///
       (lfit prison spending if time == "2015"), ///
        ytitle("Prison population per 100,000 inhabitants") ///
        xtitle("Total social spending as % of GDP") ///
        legend(order(2 "Linear fit, explained variance = `r2'%") pos(1) ring(0)) ///
        name(f2015, replace)

Feb 19, 2018

Random graphs (126): Turning tables into figures

sdmxuse data ESTAT, dataset(lfsa_epgar) start(2010) end(2010) clear

keep if inlist(geo, "AT", "BE", "BG", "CY", "CZ", "DK", "EE", "FI") ///
      | inlist(geo, "FR", "DE", "EL", "HU", "IE", "LT", "NL", "NO") ///
      | inlist(geo, "PL", "PT", "ES", "SE", "CH", "UK") 
keep if age == "Y_GE15"

replace geo = "GR" if geo == "EL"
kountry geo, from(iso2c)
rename NAMES_STD country

drop if sex == "T"
replace sex = "Men" if sex == "M"
replace sex = "Women" if sex == "F"
encode reason, gen(reasonno)
label var reasonno "Reasons for part-time work"

label define reasonno 1 "Care activities" ///
                      2 "Other personal reasons" ///
                      3 "Own illness, disability" 4 "Education, training" ///
                      5 "Could not find full-time job" 6 "Other", modify

replace value = value * 10
expand value
drop if missing(value)

tabplot reasonno country, by(sex, ///
                          note("{it:Note:} Bars and numbers indicate percentage of part-time workers per country" ///
                               "{it:Source:} Eurostat, lfsa_egpar, data refer to 2010.")) ///
                          percent(sex country) ///
                          showval(mlabsize(tiny) format(%6.0f)) xtitle("") ///
                          xlabel(, angle(vertical) labsize(small)) name(figure2, replace)

Feb 13, 2018

Random graphs (125): Bar graphs

clear
sdmxuse data ESTAT, dataset(lfsa_epgar)

keep if time == "2010"
keep if inlist(geo, "AT", "BE", "BG", "CY", "CZ", "DK", "EE", "FI") ///
      | inlist(geo, "FR", "DE", "EL", "HU", "IE", "LT", "NL", "NO") ///
      | inlist(geo, "PL", "PT", "ES", "SE", "CH", "UK") 
keep if age == "Y_GE15"

replace geo = "GR" if geo == "EL"
kountry geo, from(iso2c)
rename NAMES_STD country

drop if sex == "T"
replace sex = "Men" if sex == "M"
replace sex = "Women" if sex == "F"
encode reason, gen(reasonno)
label define reasonno 1 "Looking after children or incapacitated adults" ///
                      2 "Other family or personal responsibilities" ///
                      3 "Own illness or disability" 4 "In education or training" ///
                      5 "Could not find a full-time job" 6 "Other", modify
twoway bar value reasonno, horizontal by(country sex, ///
           cols(4) note("{it:Source:} Eurostat, lfsa_epgar, 2010. Respondents 15 years or older.", size(vsmall)) ///
     title("Reasons for part-time work")) ///
           ylabel(1/6, val)  ///
           ytitle("") xtitle("% of part-time workforce") ysize(12) xsize(8) 

Dec 2, 2017

Random graphs (120): Uncluttered line plots

// Use OECD data
sdmxuse data OECD, dataset(IDD) clear attributes

// Generate country variable
kountry location, from(iso3c)
rename NAMES_STD country

// Generate year variable
destring time, gen(year)

// Keep relevant data
keep if measure == "GINI"
keep if age == "TOT"
keep if definition == "CURRENT"
keep if inlist(country, "Netherlands", "Germany", "United Kingdom", "United States")
drop if methodo == "METH2012"

sort country year
twoway (connected value year if country == "Germany") ///
       (line value year if country == "Netherlands", lcolor(gs10) lpattern(solid)) ///
       (line value year if country == "United Kingdom", lcolor(gs10) lpattern(solid)) ///
       (line value year if country == "United States", lcolor(gs10) lpattern(solid)) ///
      , legend(off) name(pa, replace) title(Germany) xtitle("") ytitle("Income inequality") ///
        ylabel(, format(%6.2f)) 
twoway (connected value year if country == "Netherlands") ///
       (line value year if country == "Germany", lcolor(gs10) lpattern(solid)) ///
       (line value year if country == "United Kingdom", lcolor(gs10) lpattern(solid)) ///
       (line value year if country == "United States", lcolor(gs10) lpattern(solid)) ///
      , legend(off) name(pb, replace) title(Netherlands) xtitle("") ytitle("Income inequality") ///
        ylabel(, format(%6.2f)) 
twoway (connected value year if country == "United Kingdom") ///
       (line value year if country == "Germany", lcolor(gs10) lpattern(solid)) ///
       (line value year if country == "Netherlands", lcolor(gs10) lpattern(solid)) ///
       (line value year if country == "United States", lcolor(gs10) lpattern(solid)) ///
      , legend(off) name(pc, replace) title(United Kingdom) xtitle("") ytitle("Income inequality") ///
        ylabel(, format(%6.2f)) 
twoway (connected value year if country == "United States") ///
       (line value year if country == "Germany", lcolor(gs10) lpattern(solid)) ///
       (line value year if country == "Netherlands", lcolor(gs10) lpattern(solid)) ///
       (line value year if country == "United Kingdom", lcolor(gs10) lpattern(solid)) ///
      , legend(off) name(pd, replace) title(United States) xtitle("") ytitle("Income inequality") ///
        ylabel(, format(%6.2f))
    
graph combine pa pb pc pd, col(2) name(fig1, replace)

Nov 17, 2017

Random graphs (119): Line plots and dot plots

// Prepare ESS round 8
use cntry essround wrkctra dweight using "ESS8e01.dta", clear
recode wrkctra (6 = .a) (7 = .b) (8 = .c) (9 = .d)

// Add ESS rounds 1-7
append using "ESS1-7e01.dta", keep(cntry essround wrkctr wrkctra dweight)

  // Prepare variables
generate nocontract = (wrkctra == 3) if !missing(wrkctra)
kountry cntry, from(iso2c)
rename NAMES_STD country

  // Prepare files for post commands
tempname foo1
tempname foo2
postfile `foo1' str20 country essround ll nocontract ul using `foo2', replace

qui levelsof country, local(country)

 // Loop
foreach x of local country {
 foreach i of numlist 1/8 {
  capture logit nocontract [pw = dweight] if country == "`x'" & essround == `i'
  if _rc == 0 {
   qui margins [pw = dweight]
   matrix prevs = r(table)
   local prev = prevs[1,1] * 100
   local ll = prevs[5,1] * 100
   local ul = prevs[6,1] * 100
   *di "`x'" _skip(5) `i' _skip(5)  `ll' _skip(5) `prev' _skip(5) `ul'
   post `foo1' ("`x'") (`i') (`ll') (`prev') (`ul')
  }
 }
}
postclose `foo1'

// Plot estimates
use `foo2', clear

  // Fix value label
label define essround 1 "2002" 2 "2004" 3 "2006" 4 "2008" ///
                      5 "2010" 6 "2012" 7 "2014" 8 "2016", modify
label val essround essround

// First plot
sort country essround
twoway (rarea ll ul essround, lcolor(white)) ///
       (connected nocontract essround), ///
        by(country, ///
           note("") ///
           legend(off)) ///
        xlabel(1/8, val ang(90)) ///
        xtitle("") ytitle("% without job contract") ///
        name(figure2a, replace) ysize(9)

// Second plot
reshape wide ll ul nocontract, i(country) j(essround)    

scores average =  mean(nocontract*)
egen order_ = rank(average), unique
labmask order_, value(country)
    
twoway (dot nocontract1 order_, horizontal) ///
       (dot nocontract2 order_, horizontal) ///
       (dot nocontract3 order_, horizontal) ///
       (dot nocontract4 order_, horizontal) ///
       (dot nocontract5 order_, horizontal) ///
       (dot nocontract6 order_, horizontal) ///
       (dot nocontract7 order_, horizontal) ///
       (dot nocontract8 order_, horizontal) ///
       (rspike ul1 ll1 order_, horizontal) ///
       (rspike ul2 ll2 order_, horizontal) ///
       (rspike ul3 ll3 order_, horizontal) ///
       (rspike ul4 ll4 order_, horizontal) ///
       (rspike ul5 ll5 order_, horizontal) ///
       (rspike ul6 ll6 order_, horizontal) ///
       (rspike ul7 ll7 order_, horizontal) ///
       (rspike ul8 ll8 order_, horizontal), ///
        ylabel(1/32, val) ytitle("") xscale(alt) ///
        xtitle("% without job contract") ///
        legend(order(1 "2002" 2 "2004" 3 "2006" 4 "2008" ///
                     5 "2010" 6 "2012" 7 "2014" 8 "2016") ///
               pos(5) ring(0)) ///
        name(figure2b, replace) ysize(9)
   
graph combine figure2a figure2b, ///
      col(2) name(figure2, replace) ///
      note(" " "{it:Source:} European Social Survey 2002-16, weighted data. {it:Note:} Error bands/spikes denote 95% confidence intervals", span  size(*.7)) 


Nov 16, 2017

Random graphs (118): Dot plot

clear
input str5 cntry eqls2003 eqls2007 ewcs2005 ewcs2010 eusilc2014
SE 0.021949 0.030043 0.00213  0.000918 .
FI 0.022075 0.013452 0.02246  0.011247 0.00012
HR .   0.018228 0.017975 0.013302 .
SK 0.011168 0.035384 0.013425 0.019773 0.003893
CZ 0.005486 0.064484 0.008917 0.005968 0.000863
NO .   0.0226  0.021383 0.018745 0.012686
CH .   .   0.028731 .   .
HU 0.018815 0.060927 0.044574 0.013885 0.019517
SI 0.025373 0.030885 0.095199 0.019257 0.001327
NL 0.035021 0.048701 0.021501 0.034217 .
BE 0.039831 0.088688 0.025436 0.006923 0.01386
EE 0.027082 0.048187 0.052969 0.052337 0.006435
FR 0.030219 0.074314 0.040906 0.01435  .
LT 0.049985 0.077502 0.05434  0.032847 0.006778
BG 0.037858 0.063697 0.065784 0.032313 0.039127
PL 0.023636 0.075742 0.06099  0.037228 .
LU 0.106816 0.102864 0.004992 0.006159 0.032854
DE 0.090262 0.040957 0.038157 0.035452 .
RO 0.063563 0.072842 0.070762 0.022769 .
LV 0.09474  0.077167 0.054927 0.034465 0.038258
IT 0.040173 0.128064 0.06421  0.036467 .
AT 0.057465 0.132496 0.095462 0.05458  .
ES 0.112064 0.127856 0.086716 0.076224 0.038867
DK 0.129036 0.103272 0.107504 0.040896 .
UK 0.120762 0.124342 0.150114 0.083238 0.024998
ME .   .   .   0.101533 .
PT 0.173582 0.179532 0.073722 0.113514 0.091105
RS-KM .   .   .   0.160115 .
MK .   0.194579 .   0.128292 .
IE 0.270422 0.359196 0.293468 0.240577 0.03082
AL .   .   .   0.275311 .
GR 0.404795 0.53023  0.286437 0.292037 0.144072
MT 0.302118 0.465496 0.387637 0.277371 .
CY 0.322423 0.54425  0.436497 0.395157 .
TR 0.564689 0.496668 0.689807 0.643683 .
end

scores average = mean(eqls2003 eqls2007 ewcs2005 ewcs2010)

kountry cntry, from(iso2c) marker
rename NAMES_STD country
replace country = "Kosovo" if country == "rskm"

egen order_ = rank(average), unique
labmask order_, value(country)

twoway (dot eqls2003 order_, horizontal) ///
       (dot eqls2007 order_, horizontal) ///
       (dot ewcs2005 order_, horizontal) ///
       (dot ewcs2010 order_, horizontal) ///
       (dot eusilc2014 order_, horizontal) ///
      , ylabel(1/35, val) ysize(9) ///
        ytitle("") xscale(alt) ///
        xtitle("Proportion without job contract") ///
        legend(order(1 "EQLS 2003" ///
                     2 "EQLS 2003" ///
                     3 "EWCS 2005" ///
                     4 "EWCS 2010" ///
                     5 "EU-SILC 2014") title("Data source") pos(5) ring(0))

Nov 7, 2017

Random graphs (116): Histograms

use "ESS8e01.dta", clear

kountry cntry, from(iso2c) marker
rename NAMES_STD country

recode lrscale (77 88 99 = .)

histogram lrscale, by(country, note("")) ///
                   percent discrete ///
                   xlabel(0 (2) 10, val) ///
                   ylabel(0 (10) 50) ///
                   xtitle("Placement on left-right scale") ///
                   name(figure1, replace)

Oct 11, 2017

Random graphs (114): Line plot and choropleth

use ESS1-7e01, clear

// Country name variable
kountry cntry, from(iso2c) marker
rename NAMES_STD country

// Create No contract variable
gen nocontract = (wrkctra == 3) if !missing(wrkctra)

// Calculate per year and country
preserve
statsby cont = _b[_cons] contse = _se[_cons], by(country essround) clear: regress nocontract

replace cont = cont * 100             // Convert proportion into precentage
generate  lb = cont - (contse * 100)
generate  ub = cont + (contse * 100)

label define essround 1 "2002" 2 "2004" 3 "2006" 4 "2008" 5 "2010" 6 "2012" 7 "2014", modify

sort essround country
twoway (rarea lb ub essround) ///
       (connected cont essround), ///+
        by(country, legend(off) note(" " "{it:Source:} ESS 2002-2014", span) ///
        title("{bf:A}", justification(left) bexpand span)) ///
        xtitle("") xlabel(1/7, val ang(45)) ytitle("% no contract") ///
        xsize(6) ysize(6) ///
        name(figurea, replace) 
restore
  
// Calculate average % no contracts per country
collapse nocontract, by(cntry)
replace nocontract = nocontract * 100
format nocontract %6.1f
saveold cont, replace
  
// Read in map data
  // Source: shapefile from http://www.naturalearthdata.com/downloads/10m-cultural-vectors/
shp2dta using "maps\ne_10m_admin_0_countries", database(database)  coordinates(coordinates) genid(id) replace

  // Restrict coordinates to Europe
  // Source: https://en.wikipedia.org/wiki/Extreme_points_of_Europe
use coordinates, clear
replace _Y = . if _Y < 36
replace _Y = . if _Y > 71 & !missing(_Y)
replace _X = . if _X < -28 
replace _X = . if _X > 33 & !missing(_X)
saveold europecoordinates, replace

  // Create data set with Europe internal borders
clonevar id = _ID
merge m:1 id using database, nogenerate
keep if CONTINENT == "Europe"
saveold europe, replace

  // Merge map data with set with data to be plotted
use ISO_A2 NAME id using database, clear
rename ISO_A2 cntry
replace cntry = "FR" if NAME == "France" // Somehow not correct in map
replace cntry = "NO" if NAME == "Norway" // Somehow not correct in map
drop if cntry == "-99"
merge 1:1 cntry using cont, keep(matched) nogenerate

spmap nocontract using europecoordinates, id(id) xsize(6) ysize(6) ///
                                     polygon(data(europe)) legstyle(2) clnumber(9) ///
                                     legend(position (9) ring(0)) fcolor(Oranges) ///
                                     legorder(hilo) ocolor(none ..) ///
                                     title("{bf:B}", justification(left) bexpand span) ///
                                     legtitle("{bf:% no contract, 2002-2014 averages}") legjunction({c 150}) ///
                                     note(" " "{it:Source:} ESS 2002-2014", span) name(figureb, replace)
          
graph combine figurea figureb, row(1) xsize(12)

Sep 7, 2017

Random graphs (112): Line plot

clear 
// Open Eurostat data
unzipfile "macrodata\lfsi_pt_a.zip"
insheet using lfsi_pt_a_1_Data.csv

// Prepare variables
replace value = "." if value == ":"
destring value, gen(fixedterm)
rename time year
replace geo = "France" if geo == "France (metropolitan)"
kountry geo, from(other) stuck
rename _ISO3N_ country
kountry country, from(iso3n) to(iso2c)
rename _ISO2C_ cntry

// Select data and save
keep if year >= 2004
keep fixedterm geo year cntry
save lfs_fixedterm, replace

// Open ESS data
use essround agea mnact wrkctra pspwght cntry using ESS1-7e01, clear

// Select data
keep if essround >= 2
keep if inrange(agea, 20, 64)
keep if mnact == 1

// Prepare variables
generate ess_fixedterm = (wrkctra == 2)
replace  ess_fixedterm = (ess_fixedterm * 100)
generate year = 2004 if essround == 2
replace  year = 2006 if essround == 3
replace  year = 2008 if essround == 4
replace  year = 2010 if essround == 5
replace  year = 2012 if essround == 6
replace  year = 2014 if essround == 7

// Point estimates and standard errors
statsby ess_fixedterm = _b[_cons] se = _se[_cons], clear by(cntry year): regress ess_fixedterm

// Merge Eurostat data with ESS data
merge 1:1 cntry year using lfs_fixedterm

// Select countries 
drop if inlist(cntry, "RU", "IL", "UA", "LV", "MK", "MT", "RO")

// Generate country name variable
kountry cntry, from(iso2c) 
ren NAMES_STD country

// Calculate confidence intervals
generate lb = ess_fixedterm - 1.96 * se
generate ub = ess_fixedterm + 1.96 * se

// Plot figure
sort year
twoway (rarea ub lb year, lcolor(white)) ///
       (connected ess_fixedterm year) ///
       (line fixedterm year), by(country, note("")) ///
        xtitle("") ytitle("Percentage of total employed (20{c 150}64 y)" "on temporary contract") ///
        legend(order(2 "ESS" 1 "95% CI" 3 "Eurostat") row(1)) xlabel(2004 (2) 2014)


Jul 10, 2017

Using -sdmxuse- to download Eurostat data


// 1) Download data:
sdmxuse data ESTAT, dataset(ilc_di12) clear attributes
destring time, gen(year)

// Generate country name variable
replace geo = "GR" if geo == "EL"
kountry geo, from(iso2c) marker
rename NAMES_STD country
replace country = "Croatia" if country == "Yugoslavia"
drop if MARKER == 0 // Drop EU-28 etc. entries
drop if country == "European Union"
drop MARKER

// Identify EU-15
generate eu15 = (inlist(geo, "AT", "BE", "DK", "FI", "FR", "DE", "GR", "IE") ///
               | inlist(geo, "IT", "LU", "NL", "PT", "ES", "SE", "UK")) 

sparkline value year if eu15, over(country) ysize(10) ///
          note(" " "{it: Source:} Eurostat, ilc_di12, date of extraction: 2017-07-10", span) ///
          xlabel(1995 (10) 2015) xmtick(1995 (5) 2015) ///
          xtick(1995 (1) 2016) ///
          ytitle(" ") xtitle("") ///
          title("Income inequality") ///
          subtitle("(Gini of equivalised disposable income)") ///
          name(regular, replace)
// 2) Download data as time series: sdmxuse data ESTAT, dataset(ilc_di12) clear timeseries destring time, gen(year) twoway (scatter gini_hnd_uk_a year, connect(L)) /// (scatter gini_hnd_de_a year, connect(L)) /// , xtitle("") /// ytitle("Income inequality" /// "(Gini of equivalised disposable income)") /// xlabel(1995 (5) 2015) xtick(1995 (1) 2015) /// ylabel(25 (5) 35) ytick(25 (1) 35) /// note(" " "{it: Source:} Eurostat, ilc_di12, date of extraction: 2017-07-10", span) /// legend(order(1 "United Kingdom" 2 "Germany") pos(5) ring(0)) /// name(timeseries, replace)

Random graphs (101): Sparklines

import delimited une_rt_a_1_Data.csv, clear

/*
DATASET: Unemployment by sex and age - annual average [une_rt_a]
LAST UPDATE: 03.07.17 07:40:41
EXTRACTION DATE: 09.07.17 23:38:36
SOURCE OF DATA: Eurostat
*/

drop if geo == "United States"
keep if unit == "Percentage of active population"
drop sex age unit flagandfootnotes


// Generate country variable
kountry geo, from(other) stuck 
ren _ISO3N_ country
kountry  country, from(iso3n) to(iso2c)
ren  _ISO2C_ cntry
replace cntry = "UK" if cntry == "GB"

// Fix unemployment rate
replace value = "" if value == ":"          // Fix missing data indicator 
destring value, replace                     // Convert to numeric

// Line plot
twoway (line value time), by(geo,  ///
                             note(" " "{it: Source:} Eurostat, une_rt_a, date of extraction: 2017-07-09", span)) ///
                          xlabel(1990 (10) 2010) xtick(1987 (1) 2016) xmtick(1990 (5) 2015) ///
                          xtitle("") ytitle("Male unemployment rate, 25-74 y.") ///
                          name(byplot, replace)

twoway (line value time if cntry == "ES")  ///
       (line value time if cntry == "FR")  ///
       (line value time if cntry == "IE")  ///
       (line value time if cntry == "BE")  ///
       (line value time if cntry == "NL")  ///
       (line value time if cntry == "UK")  ///
      , legend(order(1 "Spain" 2 "France" 3 "Ireland" ///
                     4 "Belgium" 5 "Netherlands" 6 "UK")) ///
        note(" " "{it: Source:} Eurostat, une_rt_a, date of extraction: 2017-07-09", span) ///
        xlabel(1990 (5) 2015) xmtick(1987 (1) 2016) ///
        xtitle("") ytitle("Male unemployment rate, 25-74 y.") ///
        name(lineplot, replace)
   
// Sparklines
sparkline value time, over(geo) xlabel(1990 (5) 2015) xmtick(1987 (1) 2016) ///
                      ytitle("") xtitle("") title("Male unemployment rate, 25-74 y.") ///
                      subtitle("") ///
                      note(" " "{it: Source:} Eurostat, une_rt_a, date of extraction: 2017-07-09", span) ///
                      name(sparklines, replace) 

graph combine sparklines byplot lineplot, col(1) ysize(15) xsize(6)

Jun 20, 2017

Random graphs (100): Labeling lines directly

import delimited une_rt_a_1_Data.csv, clear

/*
DATASET: Unemployment by sex and age - annual average [une_rt_a]
LAST UPDATE: 14.06.17 13:10:19
EXTRACTION DATE: 18.06.17 11:35:33
SOURCE OF DATA: Eurostat
*/

drop sex age unit flagandfootnotes

// Generate country variable
kountryadd "Germany (until 1990 former territory of the FRG)" to "Germany" add
kountry geo, from(other) stuck marker
ren _ISO3N_ country
kountry  country, from(iso3n) to(iso2c)
ren  _ISO2C_ country_str
replace country_str = "UK" if country_str == "GB"
list country_str geo

// Fix unemployment rate
replace value = "" if value == ":"          // Fix missing data indicator 
destring value, replace                     // Convert to numeric

twoway (line value time if country_str == "UK") ///
       (line value time if country_str == "US") ///
       (scatteri 4 2016 "United States" 3.5 2016 "United Kingdom", msymbol(none)) ///
      , legend(off) ///
        xtitle("") ytitle("Male unemployment rate, 25-74 y.") ///
        xlabel(1985(5)2015) ///
        xscale(range(1983 2023)) ///
        note(" " "{it: Source:} Eurostat, une_rt_a, date of extraction: 2017-06-18", span)

Jun 18, 2017

Random graphs (98): Shaded areas

import delimited une_rt_a_1_Data.csv, clear

/*
DATASET: Unemployment by sex and age - annual average [une_rt_a]
LAST UPDATE: 14.06.17 13:10:19
EXTRACTION DATE: 18.06.17 11:35:33
SOURCE OF DATA: Eurostat
*/

drop sex age unit flagandfootnotes

// Generate country variable
kountryadd "Germany (until 1990 former territory of the FRG)" to "Germany" add
kountry geo, from(other) stuck marker
ren _ISO3N_ country
kountry  country, from(iso3n) to(iso2c)
ren  _ISO2C_ country_str
replace country_str = "UK" if country_str == "GB"
list country_str geo

// Fix unemployment rate
replace value = "" if value == ":"          // Fix missing data indicator 
destring value, replace                     // Convert to numeric

// Plot
twoway (scatteri 12 2008 12 2012, recast(area) bcolor(gs14)) ///
       (line value time if country_str == "UK") ///
       (line value time if country_str == "DE") ///
       (line value time if country_str == "US") ///
      , legend(order(2 "UK" 3 "Germany" 4 "US") ///
               pos(7) ring(0)) ///
        xtitle("") ytitle("Male unemployment rate, 25-74 y.") xtick(1983(1)2016) ///
        xlabel(1985(5)2015) ///
        note(" " "{it: Source:} Eurostat, une_rt_a, date of extraction: 2017-06-18", span)

Aug 2, 2016

Random graphs (90): Regression coefficients

version 14
use 7348_F1.dta, clear

// Prepare variables:
// Country variable
rename Y11_Country ctry
decode ctry, gen(country)
kountryadd "Macedonia (FYROM)" to "Macedonia" add
kountry country, from(other) stuck
rename _ISO3N_ geo
kountry geo, from(iso3n) to(iso2c)
rename _ISO2C_ cntry
replace cntry = "XK" if country == "Kosovo"
drop geo 

label define Y11_Country 30 "Macedonia", modify

// Wave identifier
rename Wave wave

// Gender
generate female = (Y11_HH2a == 2)

// Work-family conflict
*factor Y11_Q12a Y11_Q12b Y11_Q12c, pcf
*tab Y11_Q12a wave, mis
*tab Y11_Q12b wave, mis
*tab Y11_Q12c wave, mis
*alpha Y11_Q12a Y11_Q12b Y11_Q12c, item
scores wfb = mean(Y11_Q12a Y11_Q12b Y11_Q12c)
generate wfc = 5 - wfb
drop wfb

eststo clear

levelsof wave, local(wave)

foreach x of local wave {
eststo: mixed wfc female || ctry: female if wave == `x', cov(uns)

preserve
// Get no. of countries
matrix groups = e(N_g)
local n_g = groups[1,1]

// Predict residuals
predict u1 u0, reffects
predict u1se u0se, reses

// Calculate posterior slope
generate eb_female = u1 + _b[female]

// Plot posterior slope
egen pickone = tag(country)  // Keep one case per countr
keep if pickone
   
egen order_ = rank(-u1), unique
labmask order_, value(ctry) decode

gen high = u1 + _b[female] + (1.96 * u0se)
gen low  = u1 + _b[female] - (1.96 * u0se)
local avg =  _b[female]

twoway (rcap eb_female eb_female order_, horizontal) ///
       (rspike high low order_, horizontal) , ///
        xline(`avg') ylabel(1/`n_g', val ang(h)) ///
        ytitle("") ///
  xscale(alt) ///
        xlabel(-.2 (.1) .4) ///
        xtitle("Female WFC disadvantage") ///
        legend(off) ///
        title(`: label (wave) `x'') ///
        name(emp_bayes_`x', replace) xsize(3) nodraw
restore
}

graph combine emp_bayes_1 emp_bayes_2 emp_bayes_3, col(3) xsize(6) name(variation, replace) altshrink ///
      note("{it:Source:} European Quality of Life Surveys, 2003-11. {it:Notes:} Horizontal line shows average coefficient, country-specific" ///
        "estimates indicate deviation from this average. Error bars are 95% CI's based on random-effects models.")

coefplot est1, bylabel(EQLS 2003) || /// est2, bylabel(EQLS 2007) || /// est3, bylabel(EQLS 2011) || /// , xlabel(0 (.05) .2) drop(_cons) xscale(alt) baselevel coeflabel(female = "Female") /// xtitle("Female WFC disadvantage") xline(0) byopts(row(1)) ciopts(recast(rcap))
coefplot est1 est2 est3, xlabel(0 (.05) .2) drop(_cons) xscale(alt) baselevel coeflabel(female = "Female") /// xtitle("Female WFC disadvantage") xline(0) byopts(row(1)) ciopts(recast(rcap)) /// legend(order(2 "EQLS 2003" 4 "EQLS 2007" 6 "EQLS 2011"))

Jun 2, 2016

Random graphs (89): Bar graph

clear

// Read in data
import excel "http://hdr.undp.org/sites/default/files/composite_tables/2015_Statistical_Annex_Table_5.xls", ///
       sheet("Table 5") cellrange(B11:C188)

// Prepare country variables
rename B country
drop if country == "HIGH HUMAN DEVELOPMENT"
drop if country == "MEDIUM HUMAN DEVELOPMENT"
drop if country == "LOW HUMAN DEVELOPMENT"

kountryadd "Venezuela (Bolivarian Republic of)" to "Venezuela" add
kountryadd "Bolivia (Plurinational State of)" to "Bolivia" add
kountry country, from(other) stuck
rename _ISO3N_ geo
kountry geo, from(iso3n) to(iso2c)
rename _ISO2C_ cntry
drop geo 

// Prepare GII variable
rename C gii
label var gii "Gender Inequality Index"
replace gii = "" if gii == ".."
destring gii, replace

// Identify countries included in the ESS round 3
generate ess = (inlist(cntry, "AT", "BE", "BG", "CY", "DK", "EE", "FI", "FR") ///
              | inlist(cntry, "DE", "HU", "IE", "NL", "NO", "PL", "PT", "RU") ///
              | inlist(cntry, "SK", "SI", "ES", "SE", "CH", "UA", "GB"))

// Sort countries by GII
egen order_ = rank(gii), unique

// Plot
twoway (bar gii order_, horizontal) ///
       (bar gii order_ if ess, horizontal fcolor(gs1)) ///
      , ysize(8) legend(order(1 "All countries" 2 "Countries in ESS round 3") ring(0)) ///
        xscale(alt) ytitle("") ylabel(none) xlabel(0 (.1) .8, grid) ///
        note(" " "{it:Source:} Human Development Report 2015, Table 5.", span)

May 4, 2016

Random graphs (80): Line plots using the -by- option

unzipfile output961465243413697143.zip, replace

use ESS1-6e01_1_F1.dta, clear

// Label waves
label define essround 1 "2002" 2 "2004" 3 "2006" 4 "2008" 5 "2010" 6 "2012"
label val essround essround 

// Keep only countries that contribute six observations
egen pickone = tag(cntry essround)
tab cntry essround if pickone // Look at no. of waves per country
egen numrounds = total(pickone), by(cntry) // Calculate no. of waves per country
keep if numrounds == 6

// Identify migrants
generate migrant = 1 if (brncntr == 2) & !missing(brncntr)
replace  migrant = 2 if (brncntr == 1 & (facntr == 2 | mocntr == 2)) & !missing(brncntr, facntr, mocntr)
replace  migrant = 0 if (brncntr == 1 &  facntr == 1 & mocntr == 1) & !missing(brncntr, facntr, mocntr)

label define migrant 0 "Native" 1 "First-generation migrant" 2 "Second-generation migrant"
label value migrant migrant

// Generate country identifier
kountry cntry, from(iso2c)
rename NAMES_STD country
replace country = "Slovenia" if country == "si"

// By country, year, and migrant status
collapse (mean) imbgeco imueclt imwbcnt [pweight = dweight], by(country essround migrant)

drop if migrant == .

sort country migrant essround
twoway (connected imbgeco essround if migrant == 0, ///
         by(country, note(" " "{it:Source:} European Social Survey, rounds 1{c 150}6, weighted data", span size(*.8)))) ///
       (connected imbgeco essround if migrant == 1) ///
       (connected imbgeco essround if migrant == 2) ///
      , xlabel(1/6, val ang(v)) ytitle("Immigration good for economy") ysize(8) xtitle("") name(imbgecocym, replace) ///
        legend(order(1 "Natives" ///
                     2 "First-gen." ///
                     3 "Second-gen.") ring(0) row(1)) 

Apr 30, 2016

Random graphs (79): Means with confidence intervals

use ZA5900_v3-0-0.dta, replace

renvars, lower // Switch variable names to lower case

// Fix country variable
generate cntry = c_alphan
replace  cntry = "GB" if cntry == "GB-GBN"
replace  cntry = "DE" if cntry == "DE-E"   | cntry == "DE-W"
replace  cntry = "BE" if cntry == "BE-BRU" | cntry == "BE-WAL" | cntry == "BE-FLA" 

// Generate country name variable
kountry cntry, from(iso2c)
encode NAMES_STD, gen(country)
drop NAMES_STD

// Happiness variable
recode v55 (1 = 6) (2 = 5) (3 = 4) (4 = 3) (5 = 2) (6 = 1) (7 = 0) (0 8 9 = .), gen(lsat)

label define lsat 0 "Completely unhappy" ///
                  1 "Very unhappy" ///
                  2 "Fairly unhappy" ///
                  3 "Neither happy nor unhappy" ///
                  4 "Fairly happy" ///
                  5 "Very happy" ///
                  6 "Completely happy"
label val lsat lsat
label var lsat "Happiness"

// Plot means by country
preserve
statsby mean_ = _b[_cons] ///
        loci  = (_b[_cons] - 1.96 * _se[_cons]) ///
        hici  = (_b[_cons] + 1.96 * _se[_cons]) ///
      , by(country) total clear: ///
        regress lsat

replace country = 1000 if country == .
label define country 1000 "{bf: Total}", modify

egen order_ = rank(mean_), unique
labmask order_, value(country) decode

twoway (rcap mean_ mean_ order_, horizontal) ///
       (rspike loci hici order_, horizontal) ///
      , legend(off) ylabel(1/41, valuelabels ang(h) labsize(*.8)) ///
        xlabel(3.5 (.5) 5.0, grid format(%6.1f)) name(lsat, replace)  ///
        xmtick(3.5 (.25) 5.0, grid) ///
        ytitle("") xtitle("Average happiness") xscale(alt) ysize(8) ///
        note(" " ///
             "{it:Note:} Happiness ranges from 0 ('Completely unhappy') to 6 ('Completely happy')" ///
             "{it:Source:} ISSP 2012, doi:10.4232/1.12339" , span size(*.8))
restore

Apr 26, 2016

Random graphs (75): Line plots

use essround cntry netuse dweight using ESS1-6e01_0_F1.dta, clear

// Drop parts of data and label wave identifier
drop if essround == 6 // Doesn't have internet use variable
drop if inlist(cntry, "IS", "LT") // drop countries with only one measurement
label define essround 1 "2002" 2 "2004" 3 "2006" 4 "2008" 5 "2010"
label val essround essround 

// Generate variable of interest
generate dailyuser = (netuse == 7) if !missing(netuse)

// Generate values by country and round
collapse (mean) dailyuser [pweight = dweight], by(cntry essround)
replace dailyuser = dailyuser * 100

// Generate country identifier
kountry cntry, from(iso2c)
rename NAMES_STD country

// Plot
twoway (connected dailyuser essround, ///
        by(country, note(" " "{it:Source:} European Social Survey, rounds 1{c 150}5, weighted data", span size(*.8)) ///
     col(3))), xlabel(, val) ytitle("% daily internet users") ysize(8) xtitle("")

Mar 14, 2016

Random graphs (65): Dot plots with confidence intervals

preserve
// Keep those countries for which three waves are available
keep if inlist(cntry, "AT", "AU", "BG", "CZ", "DEE", "DEW", "ES", "GB", "HU") | ///
        inlist(cntry, "IE", "IL", "JP", "NL", "NO", "PH", "PL", "RU", "SE")   | ///
  inlist(cntry, "SI", "US")

// Define temporary objects
tempname foo
tempname foox
postfile `foo' str3 cntry year perc perc_ll perc_ul using `foox', replace

levelsof cntry, local(levels1)
levelsof year, local(levels2)

// Calculate proportions by country and year
foreach year of local levels2 {
 foreach country of local levels1 {

    capture proportion separate if cntry == "`country'" & year == `year'
    *matrix list r(table)
    matrix fcoefs  = r(table)
    local fperc    = fcoefs[1,2] * 100
    local fperc_ll = fcoefs[5,2] * 100
    local fperc_ul = fcoefs[6,2] * 100

    di "`country'"  _skip(2) `year' _skip(2)  `fperc_ll' _skip(2) `fperc' _skip(2) `fperc_ul'

    if "`fperc'" != "" {    // Make sure that the loop doesn't break if empty
    post `foo' ("`country'") (`year') (`fperc') (`fperc_ll') (`fperc_ul')
    }
 }
}
postclose `foo'

// Use posted data set
use `foox', clear

// Generate country name variable using -kountry-
kountry cntry, from(iso2c)
rename NAMES_STD country
replace country = "Germany (West)" if country == "dew"
replace country = "Germany (East)" if country == "dee"

// Plot average change over time
twoway (scatter perc year, connect(direct) msymbol(o)) ///
       (rcap perc_ll perc_ul year) ///
      , by(country, ///
           note("{it:Source:} ISSP 'Family and Changing Gender Roles II{c 150}IV. {it:Note:} Error bars denote 95% confidence intervals.", span) ///
           legend(off)) ///
        xlabel(1994 2002 2012) xtitle("") ///
        ytitle("% of couples keeping incomes separate") ///
        ylabel(0 10 20 30 40 50, gstyle(minor)) yscale(r(0))
        // yscale(r(0)) adds missing gridline according to
        // http://www.stata.com/statalist/archive/2013-04/msg00904.html    
restore

Feb 22, 2016

Random graphs (60): Line plots

import delimited C:\internet\isoc_bdek_di_1_Data.csv, clear

// Generate country variable
kountryadd "Germany (until 1990 former territory of the FRG)" to "Germany" add
kountry geo, from(other) stuck marker
ren _ISO3N_ country
kountry  country, from(iso3n) to(iso2c)
ren  _ISO2C_ country_str
replace country_str = "UK" if country_str == "GB"

replace country_str = "EU25" if geo == "European Union (25 countries)"
replace country_str = "EU27" if geo == "European Union (27 countries)"
replace country_str = "EU28" if geo == "European Union (28 countries)"
replace country_str = "EU15" if geo == "European Union (15 countries)"
drop if geo == "Euro area (EA11-2000, EA12-2006, EA13-2007, EA15-2008, EA16-2010, EA17-2013, EA18-2014, EA19)"
drop MARKER country
*list country_str geo

// Fix variables
drop ind_type // Drop constant 
replace value = "" if value == ":"          // Fix missing data indicator 
destring value, replace                     // Convert to numeric
encode indic_is, gen(indic)                 // Convert from string
label var time "Time"

// Keep relevant cases
keep if unit == "Percentage of individuals"
drop if inlist(country_str, "CH", "EU25", "EU28", "ME", "RS")
twoway (line value time if indic == 1, by(country_str, note("{it:Source:} Eurostat, isoc_bdek_di", span))), ///
        ytitle("% who access internet at least once a week") ///
        xlabel(2003 2005 2010 2015, ang(h) alternate) xtitle("") ///
        name(graph1, replace)

// All in one plot
encode country_str, gen(country)
keep if indic == 1
xtset country time, yearly
   
keep if inlist(country, 6, 7, 8, 10, 16, 19, 25, 29, 30, 34) // Reduce number of countries
xtline value, overlay xlabel(2003 2005 2010 2015, ang(h)) xtitle("") ///
              ytitle("% who access internet at least once a week") ///
              legend(pos(2)) name(graph2, replace) ///
              note("{it:Source:} Eurostat, isoc_bdek_di", span)xlabel(2003 2005 2010 2015, ang(h) alternate) xtitle("") ///
              name(graph2, replace)