From 592b1e2e81c6b55f8c71a59bf21baa8a91b783d8 Mon Sep 17 00:00:00 2001 From: ivilaco Date: Wed, 22 Nov 2023 19:40:14 -0500 Subject: [PATCH 1/5] Code update MSNA Adding the folder with STATA and R codes to process the MSNA --- .../61635561/pcs/debug-breakpoints.pper | 21 + .../.Rproj.user/61635561/pcs/files-pane.pper | 9 + .../.Rproj.user/61635561/pcs/source-pane.pper | 3 + .../61635561/pcs/windowlayoutstate.pper | 14 + .../61635561/pcs/workbench-pane.pper | 5 + .../msna/.Rproj.user/61635561/rmd-outputs | 5 + .../.Rproj.user/61635561/saved_source_markers | 1 + .../61635561/sources/per/t/3B4BA8D5 | 24 + .../61635561/sources/per/t/3B4BA8D5-contents | 134 + .../61635561/sources/per/t/4024B0B1 | 26 + .../61635561/sources/per/t/4024B0B1-contents | 47 + .../61635561/sources/per/t/6A803CB2 | 24 + .../61635561/sources/per/t/6A803CB2-contents | 147 + .../61635561/sources/per/t/6C154361 | 24 + .../61635561/sources/per/t/6C154361-contents | 67 + .../61635561/sources/per/t/886A5C1D | 24 + .../61635561/sources/per/t/886A5C1D-contents | 285 ++ .../61635561/sources/per/t/B115ECF0 | 24 + .../61635561/sources/per/t/B115ECF0-contents | 257 ++ .../61635561/sources/per/t/DC9E5889 | 24 + .../61635561/sources/per/t/DC9E5889-contents | 53 + .../61635561/sources/prop/0150AB14 | 4 + .../61635561/sources/prop/5A2FCE8E | 4 + .../61635561/sources/prop/99A3BEB2 | 4 + .../61635561/sources/prop/9C16D759 | 4 + .../61635561/sources/prop/A7EEAFB5 | 4 + .../61635561/sources/prop/BE6B4DA0 | 4 + .../61635561/sources/prop/FFCEA998 | 6 + .../.Rproj.user/61635561/sources/prop/INDEX | 7 + .../shared/notebooks/patch-chunk-names | 0 notebooks/msna/0_master.R | 49 + notebooks/msna/Codes/1_cleaning.R | 53 + notebooks/msna/Codes/2_demographics.R | 76 + notebooks/msna/Codes/3_1_conflict.R | 147 + notebooks/msna/Codes/3_2_aid.R | 145 + notebooks/msna/Codes/3_3_displacement.R | 285 ++ notebooks/msna/Codes/3_4_hh_welfare.R | 257 ++ notebooks/msna/Codes/3_5_maps.R | 22 + notebooks/msna/Codes/ado/s/spmap.ado | 1604 +++++++++++ notebooks/msna/Codes/ado/s/spmap.hlp | 2355 ++++++++++++++++ notebooks/msna/Codes/ado/s/spmap_arrow.ado | 555 ++++ notebooks/msna/Codes/ado/s/spmap_color.ado | 2474 +++++++++++++++++ notebooks/msna/Codes/ado/s/spmap_diagram.ado | 1147 ++++++++ notebooks/msna/Codes/ado/s/spmap_examples.ado | 328 +++ notebooks/msna/Codes/ado/s/spmap_label.ado | 437 +++ notebooks/msna/Codes/ado/s/spmap_line.ado | 410 +++ notebooks/msna/Codes/ado/s/spmap_point.ado | 955 +++++++ notebooks/msna/Codes/ado/s/spmap_polygon.ado | 452 +++ notebooks/msna/Codes/ado/s/spmap_psl.ado | 98 + notebooks/msna/Codes/ado/s/spmap_scalebar.ado | 305 ++ notebooks/msna/Codes/ado/stata.trk | 47 + notebooks/msna/Codes/maps.do | 147 + 52 files changed, 13603 insertions(+) create mode 100644 notebooks/msna/.Rproj.user/61635561/pcs/debug-breakpoints.pper create mode 100644 notebooks/msna/.Rproj.user/61635561/pcs/files-pane.pper create mode 100644 notebooks/msna/.Rproj.user/61635561/pcs/source-pane.pper create mode 100644 notebooks/msna/.Rproj.user/61635561/pcs/windowlayoutstate.pper create mode 100644 notebooks/msna/.Rproj.user/61635561/pcs/workbench-pane.pper create mode 100644 notebooks/msna/.Rproj.user/61635561/rmd-outputs create mode 100644 notebooks/msna/.Rproj.user/61635561/saved_source_markers create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/3B4BA8D5 create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/3B4BA8D5-contents create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/4024B0B1 create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/4024B0B1-contents create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/6A803CB2 create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/6A803CB2-contents create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/6C154361 create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/6C154361-contents create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/886A5C1D create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/886A5C1D-contents create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/B115ECF0 create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/B115ECF0-contents create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/DC9E5889 create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/per/t/DC9E5889-contents create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/prop/0150AB14 create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/prop/5A2FCE8E create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/prop/99A3BEB2 create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/prop/9C16D759 create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/prop/A7EEAFB5 create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/prop/BE6B4DA0 create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/prop/FFCEA998 create mode 100644 notebooks/msna/.Rproj.user/61635561/sources/prop/INDEX create mode 100644 notebooks/msna/.Rproj.user/shared/notebooks/patch-chunk-names create mode 100644 notebooks/msna/0_master.R create mode 100644 notebooks/msna/Codes/1_cleaning.R create mode 100644 notebooks/msna/Codes/2_demographics.R create mode 100644 notebooks/msna/Codes/3_1_conflict.R create mode 100644 notebooks/msna/Codes/3_2_aid.R create mode 100644 notebooks/msna/Codes/3_3_displacement.R create mode 100644 notebooks/msna/Codes/3_4_hh_welfare.R create mode 100644 notebooks/msna/Codes/3_5_maps.R create mode 100644 notebooks/msna/Codes/ado/s/spmap.ado create mode 100644 notebooks/msna/Codes/ado/s/spmap.hlp create mode 100644 notebooks/msna/Codes/ado/s/spmap_arrow.ado create mode 100644 notebooks/msna/Codes/ado/s/spmap_color.ado create mode 100644 notebooks/msna/Codes/ado/s/spmap_diagram.ado create mode 100644 notebooks/msna/Codes/ado/s/spmap_examples.ado create mode 100644 notebooks/msna/Codes/ado/s/spmap_label.ado create mode 100644 notebooks/msna/Codes/ado/s/spmap_line.ado create mode 100644 notebooks/msna/Codes/ado/s/spmap_point.ado create mode 100644 notebooks/msna/Codes/ado/s/spmap_polygon.ado create mode 100644 notebooks/msna/Codes/ado/s/spmap_psl.ado create mode 100644 notebooks/msna/Codes/ado/s/spmap_scalebar.ado create mode 100644 notebooks/msna/Codes/ado/stata.trk create mode 100644 notebooks/msna/Codes/maps.do diff --git a/notebooks/msna/.Rproj.user/61635561/pcs/debug-breakpoints.pper b/notebooks/msna/.Rproj.user/61635561/pcs/debug-breakpoints.pper new file mode 100644 index 00000000..247f3eb8 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/pcs/debug-breakpoints.pper @@ -0,0 +1,21 @@ +{ + "debugBreakpointsState": { + "breakpoints": [ + { + "id": 0, + "path": "C:/Users/wb607344/Downloads/syria-economic-monitor/notebooks/msna/0_master.R", + "line_number": 7, + "function_steps": "", + "function_name": "toplevel", + "state": 1, + "editor_state": 1, + "editor_line_number": 7, + "is_pending_debug_completion": false, + "needs_updated_steps": false, + "type": 1, + "is_package_breakpoint": false, + "package_name": "" + } + ] + } +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/pcs/files-pane.pper b/notebooks/msna/.Rproj.user/61635561/pcs/files-pane.pper new file mode 100644 index 00000000..9690bd95 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/pcs/files-pane.pper @@ -0,0 +1,9 @@ +{ + "sortOrder": [ + { + "columnIndex": 2, + "ascending": true + } + ], + "path": "C:/Users/wb607344/Downloads/syria-economic-monitor/notebooks/msna" +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/pcs/source-pane.pper b/notebooks/msna/.Rproj.user/61635561/pcs/source-pane.pper new file mode 100644 index 00000000..902cc6f8 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/pcs/source-pane.pper @@ -0,0 +1,3 @@ +{ + "activeTab": 0 +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/pcs/windowlayoutstate.pper b/notebooks/msna/.Rproj.user/61635561/pcs/windowlayoutstate.pper new file mode 100644 index 00000000..2dd1ec8a --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/pcs/windowlayoutstate.pper @@ -0,0 +1,14 @@ +{ + "left": { + "splitterpos": 258, + "topwindowstate": "NORMAL", + "panelheight": 592, + "windowheight": 630 + }, + "right": { + "splitterpos": 387, + "topwindowstate": "NORMAL", + "panelheight": 592, + "windowheight": 630 + } +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/pcs/workbench-pane.pper b/notebooks/msna/.Rproj.user/61635561/pcs/workbench-pane.pper new file mode 100644 index 00000000..75e70e94 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/pcs/workbench-pane.pper @@ -0,0 +1,5 @@ +{ + "TabSet1": 0, + "TabSet2": 0, + "TabZoom": {} +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/rmd-outputs b/notebooks/msna/.Rproj.user/61635561/rmd-outputs new file mode 100644 index 00000000..3f2ff2d6 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/rmd-outputs @@ -0,0 +1,5 @@ + + + + + diff --git a/notebooks/msna/.Rproj.user/61635561/saved_source_markers b/notebooks/msna/.Rproj.user/61635561/saved_source_markers new file mode 100644 index 00000000..2b1bef11 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/saved_source_markers @@ -0,0 +1 @@ +{"active_set":"","sets":[]} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/3B4BA8D5 b/notebooks/msna/.Rproj.user/61635561/sources/per/t/3B4BA8D5 new file mode 100644 index 00000000..07f839f0 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/3B4BA8D5 @@ -0,0 +1,24 @@ +{ + "id": "3B4BA8D5", + "path": "C:/Users/wb607344/Downloads/syria-economic-monitor/notebooks/msna/Codes/3_2_aid.R", + "project_path": "Codes/3_2_aid.R", + "type": "r_source", + "hash": "2454355428", + "contents": "", + "dirty": false, + "created": 1700687544074.0, + "source_on_save": false, + "relative_order": 6, + "properties": { + "source_window_id": "", + "Source": "Source" + }, + "folds": "", + "lastKnownWriteTime": 1700425176, + "encoding": "UTF-8", + "collab_server": "", + "source_window": "", + "last_content_update": 1700425176, + "read_only": false, + "read_only_alternatives": [] +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/3B4BA8D5-contents b/notebooks/msna/.Rproj.user/61635561/sources/per/t/3B4BA8D5-contents new file mode 100644 index 00000000..206ae35b --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/3B4BA8D5-contents @@ -0,0 +1,134 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assesment +# 3_2_aid +###################################################################### + +# % HH having received aid in the 3 months ------------------------------------- + +aid_2022 <- msna_2022 %>% + group_by(q_k10, q_k9, q_7_1) %>% + summarise(per_aid_hh_rec = mean(q_17_1 == "Yes", na.rm = TRUE) * 100, + .groups = 'drop') + +aid_2022 <- aid_2022 %>% + mutate(subdis_code = str_split(q_k9, " - ", simplify = TRUE)[, 1], + subdis_name = str_split(q_k9, " - ", simplify = TRUE)[, 2]) %>% + select(subdis_code, subdis_name, q_k10, per_aid_hh_rec, q_7_1) %>% + rename( + type_location = q_k10, + hh_pop_type = q_7_1 + ) + +aid_2022 %>% + write_csv( + here("Data", + "Coded", + "aid_dis_2022.csv" + ) + ) + +# Aid satisfaction ------------------------------------------------------------- + +aid_2022 <- msna_2022 %>% + filter(!is.na(q_17_3)) + +unique_q_k10 <- unique(msna_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- aid_2022 %>% + filter(q_k10 == value) %>% + group_by(q_7_1, q_17_3) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + +pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_17_3))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_aid_sat_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) +} + +# Priority needs --------------------------------------------------------------- + +needs_2022 <- msna_2022 %>% + select(id, q_7_1, q_16_1_1, q_k10) %>% + rename(need = q_16_1_1) %>% + filter(need != "All needs are met") %>% + mutate(id = id, + ones = 1, + need = ifelse(need == "Shelter assistance (emergency shelter provision, shelter repairs, rent subsidies)", "Shelter assistance", need), + need = ifelse(need %in% c("Other (specify)", + "Access to community centers and safe spaces for women and girls", + "Reintegration services", "GBV post services", + "Risk awareness and clearance (Mine Action)", + "Technical and vocational training", + "No other reasons", + "Don't know/unsure", + "Waste disposal", + "Access to safe water", + "WASH services (unloading service, toilet, handbasin, associated connections/sewage system)", + "Phone/data/communication", + "Education services", + "Electricity provision", + "Disability-specific needs (medical equipment, medicine, services)", + "Health services", "Medicine", + "Mental health and psychosocial support services (e.g. structured group activities in a safe space, invididual or group counseling, etc.)"), "Other", need), + need = ifelse(need %in% c("NFI items (e.g. clothing, blankets, cooking material, sanitation items, fuel and school equipment)", "Shelter assistance"), "Shelter assistance, NFI items", need), + need = ifelse(need %in% c("Legal advice including civil documentation and Housing, Land and Property", + "Livelihood opportunities/inability to work"), "Legal advice and documentation", need)) %>% + group_by(need, q_7_1, q_k10) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(need)) %>% + group_by(q_7_1, q_k10) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + +unique_q_k10 <- unique(safety_2022$q_k10) + +for (value in unique_q_k10) { + plot_data <- filter(needs_2022, q_k10 == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = need, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Need") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("/bar_need", gsub("/", "_", value), ".png")), bar_chart, width = 9, height = 6) +} + +# GoS-issued documentation ----------------------------------------------------- diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/4024B0B1 b/notebooks/msna/.Rproj.user/61635561/sources/per/t/4024B0B1 new file mode 100644 index 00000000..ad3cbf96 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/4024B0B1 @@ -0,0 +1,26 @@ +{ + "id": "4024B0B1", + "path": "C:/Users/wb607344/Downloads/syria-economic-monitor/notebooks/msna/0_master.R", + "project_path": "0_master.R", + "type": "r_source", + "hash": "1020133309", + "contents": "", + "dirty": false, + "created": 1700687469167.0, + "source_on_save": false, + "relative_order": 1, + "properties": { + "source_window_id": "", + "Source": "Source", + "cursorPosition": "24,13", + "scrollLine": "20" + }, + "folds": "", + "lastKnownWriteTime": 1700687555, + "encoding": "UTF-8", + "collab_server": "", + "source_window": "", + "last_content_update": 1700687555444, + "read_only": false, + "read_only_alternatives": [] +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/4024B0B1-contents b/notebooks/msna/.Rproj.user/61635561/sources/per/t/4024B0B1-contents new file mode 100644 index 00000000..9fa95f0d --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/4024B0B1-contents @@ -0,0 +1,47 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assesment +# 0_master +###################################################################### + +install.packages(c("here", "tidyverse", "visdat", "summarytools", "readxl", "ggplot2", "Hmisc", "devtools")) +devtools::install_github("hadley/scales") + +library(here) +library(tidyverse) +library(readxl) +library(visdat) +library(summarytools) +library(ggplot2) +library(Hmisc) +library(scales) +library(dplyr) +library(viridis) +library(ggrepel) + +# Colors ----------------------------------------------------------------------- + +pie_colors <- c("#66c2e0", "#fae10b", "#fc8d62", "darkseagreen3", "lightpink1", "lightsteelblue1") +bar_colors <- c("#66c2e0", "#fae10b", "#fc8d62") + +# Codes ------------------------------------------------------------------------ + + # Data cleaning + source(here("Codes", "1_cleaning.R")) + + # Demographic analysis + source(here("Codes", "2_demographics.R")) + + # Thematic pillars + + # Conflict and household welfare + source(here("Codes", "3_1_conflict.R")) + + # Humanitarian Aid + source(here("Codes", "3_2_aid.R")) + + # Humanitarian Aid + source(here("Codes", "3_3_displacement.R")) + + # HH welfare + source(here("Codes", "3_4_hh_welfare.R")) diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/6A803CB2 b/notebooks/msna/.Rproj.user/61635561/sources/per/t/6A803CB2 new file mode 100644 index 00000000..93922422 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/6A803CB2 @@ -0,0 +1,24 @@ +{ + "id": "6A803CB2", + "path": "C:/Users/wb607344/Downloads/syria-economic-monitor/notebooks/msna/Codes/3_1_conflict.R", + "project_path": "Codes/3_1_conflict.R", + "type": "r_source", + "hash": "935954519", + "contents": "", + "dirty": false, + "created": 1700687533691.0, + "source_on_save": false, + "relative_order": 4, + "properties": { + "source_window_id": "", + "Source": "Source" + }, + "folds": "", + "lastKnownWriteTime": 1700422960, + "encoding": "UTF-8", + "collab_server": "", + "source_window": "", + "last_content_update": 1700422960, + "read_only": false, + "read_only_alternatives": [] +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/6A803CB2-contents b/notebooks/msna/.Rproj.user/61635561/sources/per/t/6A803CB2-contents new file mode 100644 index 00000000..3b8df903 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/6A803CB2-contents @@ -0,0 +1,147 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assessment +# 3_1_conflict +###################################################################### + +# Presence of areas where women and girls feel unsafe -------------------------- + +unsafety_2022 <- msna_2022 %>% + group_by(q_8_7, q_k10) %>% + mutate(ones = 1) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + filter(!is.na(q_8_7), q_8_7 != "Prefer not to answer") + +unsafety_2022 <- transform(unsafety_2022, percentage = total / tapply(total, q_k10, sum)[q_k10]*100) %>% + mutate(percentage = round(percentage, 0)) + +bar_chart <- ggplot(unsafety_2022, aes(x = q_k10, y = percentage, fill = q_8_7)) + + geom_bar(stat = "identity") + + geom_text(aes(label = scales::percent(percentage, scale = 1)), # Add percentage labels + position = position_stack(vjust = 0.5), # Adjust the vertical position of labels + size = 3, # Set label size + color = "black", # Set label color + show.legend = FALSE) + + labs(title = "", + x = "Location type", + y = "Percentage of households", + fill = "") + + theme_minimal() + + coord_flip() + + theme( + legend.position = "bottom", + legend.box = "horizontal" + ) + + scale_fill_manual(values = bar_colors) + +ggsave(here("Output", "bar_unsaf_girls.png"), bar_chart, width = 10, height = 6) + +# Main safety and security concerns in the past 3 months ----------------------- + +safety_2022 <- msna_2022 %>% + select(id, q_16_8, q_k10) %>% + separate( + q_16_8, + into = c("safety_1", "safety_2", "safety_3", "safety_4", "safety_5"), + sep = "; " + ) %>% + pivot_longer(cols = starts_with("safety"), names_to = "safety_q", values_to = "safety_r") %>% + filter(!is.na(safety_r), safety_r != "Don't know/unsure", safety_r != "Prefer not to answer") %>% + mutate(ones = 1, + safety_r = ifelse(safety_r %in% c("Discrimination on the basis of race, political beliefs, religion, class, age, sex, marital status (widow/divorced), disability, etc.", + "Discrimination of any sort", + "Other (please specify)", + "Physical and logistic constraints preventing mobility (roads damaged, buildings damaged, etc.)", + "Presence of UXO, IEDs, landmines, etc. around schools", + "Tensions between host communities and returnees in areas of return", + "Safety or security concerns related to displacement", + "Safety or security concerns related to conflict, i.e. including hostilities, destruction of property, threats, HH members injured/killed", + "Threat of exploitation and abuse (including of a sexual nature) in the community", + "Exploitation due to disability", + "Presence of UXO, IEDs, landmines, etc."), + "Other", safety_r)) %>% + group_by(safety_r, q_k10) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + group_by(q_k10) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + +bar_chart <- ggplot(safety_2022, aes(x = percentage, y = safety_r, fill = q_k10)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Need") + + scale_x_continuous(limits = c(0, max(safety_2022$percentage) + (max(safety_2022$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + +ggsave(here("Output", "bar_sec.png"), bar_chart, width = 9, height = 6) + + +# High levels of stress experienced by a hh member ------------------------------ + +stress_2022 <- msna_2022 %>% + select(starts_with("q_8_5_"), q_k10, q_7_1) %>% + mutate(stress = ifelse(q_8_5_0 == "Yes" | q_8_5_1 == "Yes" | q_8_5_2 == "Yes" | q_8_5_3 == "Yes", "Yes", "No"), + stress = ifelse((q_8_5_0 == "No" & is.na(stress)) | (q_8_5_1 == "No" & is.na(stress)) | (q_8_5_2 == "No" & is.na(stress)) | (q_8_5_3 == "No" & is.na(stress)), "No", stress), + ones = 1) %>% + filter(!is.na(stress)) %>% + group_by(stress, q_k10, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') + +unique_q_k10 <- unique(stress_2022$q_k10) + +for (value in unique_q_k10) { + + subset_data <- stress_2022 %>% + filter(q_k10 == value) %>% + transform(percentage = total / tapply(total, q_7_1, sum)[q_7_1]*100) %>% + mutate(percentage = round(percentage, 0)) + + bar_chart <- ggplot(subset_data, aes(x = q_7_1, y = percentage, fill = stress)) + + geom_bar(stat = "identity") + + geom_text(aes(label = scales::percent(percentage, scale = 1)), + position = position_stack(vjust = 0.5), + size = 3, + color = "black", + show.legend = FALSE) + + labs(title = value, + x = "Population type", + y = "Percentage of households", + fill = "") + + theme_minimal() + + coord_flip() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank(), + legend.position = "bottom", + legend.box = "horizontal" + ) + + scale_fill_manual(values = bar_colors) + + ggsave(here("Output", paste0("bar_stress_", gsub(" ", "_", value), ".png")), bar_chart, width = 6, height = 6.5) + +} diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/6C154361 b/notebooks/msna/.Rproj.user/61635561/sources/per/t/6C154361 new file mode 100644 index 00000000..2eaa75b7 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/6C154361 @@ -0,0 +1,24 @@ +{ + "id": "6C154361", + "path": "C:/Users/wb607344/Downloads/syria-economic-monitor/notebooks/msna/Codes/2_demographics.R", + "project_path": "Codes/2_demographics.R", + "type": "r_source", + "hash": "1770471498", + "contents": "", + "dirty": false, + "created": 1700687525889.0, + "source_on_save": false, + "relative_order": 2, + "properties": { + "source_window_id": "", + "Source": "Source" + }, + "folds": "", + "lastKnownWriteTime": 1699911677, + "encoding": "UTF-8", + "collab_server": "", + "source_window": "", + "last_content_update": 1699911677, + "read_only": false, + "read_only_alternatives": [] +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/6C154361-contents b/notebooks/msna/.Rproj.user/61635561/sources/per/t/6C154361-contents new file mode 100644 index 00000000..804442d2 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/6C154361-contents @@ -0,0 +1,67 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assessment +# 2_demographics +###################################################################### + +# Population distribution ------------------------------------------------------ + +pop_2022 <- msna_2022 %>% + group_by(q_7_1, q_k9) %>% + summarise(pop = sum(q_r12, na.rm = TRUE), + .groups = 'drop') + +pop_2022 <- pop_2022 %>% + mutate(subdis_code = str_split(q_k9, " - ", simplify = TRUE)[, 1], + subdis_name = str_split(q_k9, " - ", simplify = TRUE)[, 2]) %>% + select(subdis_code, subdis_name, q_7_1, pop) %>% + rename( + hh_pop_type = q_7_1, + ) + +pop_2022 %>% + write_csv( + here("Data", + "Coded", + "pop_2022.csv" + ) + ) + +# HH characteristics ---------------------------------------------------- + +# # HH population type +# msna_2022$q_7_1 <- factor(msna_2022$q_7_1, levels = names(sort(table(msna_2022$q_7_1), decreasing = TRUE))) +# +# ggplot(msna_2022, aes(x = q_7_1)) + +# geom_bar(fill = "skyblue", color = "darkblue", alpha = 0.7) + +# geom_text(stat = "count", aes(label = ..count..), vjust = -0.5) + # Add labels +# labs(title = "What population type is this household?", x = "Population Type", y = "Count") + +# theme_minimal() +# +# # HH members +# ggplot(msna_2022, aes(x = q_r12)) + +# geom_histogram(binwidth = 1, fill = "skyblue", color = "darkblue", alpha = 0.7) + +# labs(title = "House hold members", x = "Age", y = "Frequency") + +# theme_minimal() + +# Respondent's demographics ---------------------------------------------------- + +# # Age +# ggplot(msna_2022, aes(y = q_r2)) + +# geom_boxplot(fill = "skyblue", color = "darkblue", alpha = 0.7) + +# labs(title = "Respondent's Age", y = "Age") + +# theme_minimal() +# +# ggplot(msna_2022, aes(x = q_r2)) + +# geom_histogram(binwidth = 2, fill = "skyblue", color = "darkblue", alpha = 0.7) + +# labs(title = "Respondent's Age", x = "Age", y = "Frequency") + +# theme_minimal() +# +# # Marital status +# msna_2022$q_r3 <- factor(msna_2022$q_r3, levels = names(sort(table(msna_2022$q_r3), decreasing = TRUE))) +# +# ggplot(msna_2022, aes(x = q_r3)) + +# geom_bar(fill = "skyblue", color = "darkblue", alpha = 0.7) + +# geom_text(stat = "count", aes(label = ..count..), vjust = -0.5) + # Add labels +# labs(title = "Respondent's Marital Status", x = "Marital Status", y = "Count") + +# theme_minimal() diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/886A5C1D b/notebooks/msna/.Rproj.user/61635561/sources/per/t/886A5C1D new file mode 100644 index 00000000..048b0d88 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/886A5C1D @@ -0,0 +1,24 @@ +{ + "id": "886A5C1D", + "path": "C:/Users/wb607344/Downloads/syria-economic-monitor/notebooks/msna/Codes/3_3_displacement.R", + "project_path": "Codes/3_3_displacement.R", + "type": "r_source", + "hash": "1585581526", + "contents": "", + "dirty": false, + "created": 1700687536639.0, + "source_on_save": false, + "relative_order": 5, + "properties": { + "source_window_id": "", + "Source": "Source" + }, + "folds": "", + "lastKnownWriteTime": 1700424375, + "encoding": "UTF-8", + "collab_server": "", + "source_window": "", + "last_content_update": 1700424375, + "read_only": false, + "read_only_alternatives": [] +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/886A5C1D-contents b/notebooks/msna/.Rproj.user/61635561/sources/per/t/886A5C1D-contents new file mode 100644 index 00000000..30256d9f --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/886A5C1D-contents @@ -0,0 +1,285 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assessment +# 3_3_displacement +###################################################################### + +# If host population, have you ever been displaced? ---------------------------- +# Title: Percentage of host population households that have been displaced + +displaced_2022 <- msna_2022 %>% + filter(!is.na(q_7_2)) %>% + count(q_7_2) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(displaced_2022, aes(x = "", y = percentage, fill = fct_inorder(q_7_2))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = displaced_2022, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + ggsave(here("Output", "pie_hh_dis.png"), plot = pie_chart, width = 6, height = 6, units = "in", dpi = 300) + +# Host HHs coming back to their current location after being displaced --------- + +host_date_2022 <- msna_2022 %>% + filter(!is.na(q_7_2_1)) %>% + group_by(q_7_2_1) %>% + summarise(obs = cumsum(n())) + +time_chart <- host_date_2022 %>% + ggplot(aes(x = q_7_2_1, y = obs)) + + geom_line(color = "steelblue", size = 1.2) + + scale_y_continuous(limits = c(0, 250), expand = c(0, 0)) + + labs(title = "", + x = "Date", + y = "Households") + + theme_minimal() + + theme(axis.text.x = element_text(angle = 45, hjust = 1), + axis.title = element_text(face = "bold"), + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + panel.grid.major = element_line(color = "lightgray", linetype = "dashed"), + panel.grid.minor = element_blank(), + axis.line = element_line(color = "black")) + +ggsave(here("Output", paste0("time_host_ret", gsub(" ", "_", value), ".png")), plot = time_chart, width = 10, height = 6, units = "in", dpi = 300) + +# Where did the hh reside prior to returning to their original community ------- + +returnee_2022 <- msna_2022 %>% + filter(!is.na(q_7_4)) %>% + count(q_7_4) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(returnee_2022, aes(x = "", y = percentage, fill = fct_inorder(q_7_4))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = returnee_2022, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + ggsave(here("Output", "pie_returnee.png"), plot = pie_chart, width = 6, height = 6, units = "in", dpi = 300) + +# IDP HHs arriving to their current location ----------------------------------- + +idp_date_2022 <- msna_2022 %>% + filter(!is.na(q_7_6)) %>% + group_by(q_7_6) %>% + summarise(obs = cumsum(n())) + +time_chart <- idp_date_2022 %>% + ggplot(aes(x = q_7_6, y = obs)) + + geom_line(color = "steelblue", size = 1.2) + + scale_y_continuous(limits = c(0, 250), expand = c(0, 0)) + + labs(title = "", + x = "Date", + y = "Households") + + theme_minimal() + + theme(axis.text.x = element_text(angle = 45, hjust = 1), + axis.title = element_text(face = "bold"), + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + panel.grid.major = element_line(color = "lightgray", linetype = "dashed"), + panel.grid.minor = element_blank(), + axis.line = element_line(color = "black")) + +ggsave(here("Output", paste0("time_idp_arr", gsub(" ", "_", value), ".png")), plot = time_chart, width = 10, height = 6, units = "in", dpi = 300) + +# For IDPs, how many times have you and your HH been displaced since 2011? ----- +# Title: Times IDP households have been displaced since 2011 + +unique_q_k10 <- unique(msna_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- msna_2022 %>% + filter(!is.na(q_7_7), q_k10 == value) + + hist_chart <- ggplot(subset_data, aes(x = q_7_7)) + + geom_histogram(binwidth = 1, fill = "skyblue", color = "darkblue", alpha = 0.7) + + labs(title = value, x = "Number of Times", y = "Frequency") + + theme_minimal() + + theme(plot.title = element_text(hjust = 0.5)) # Centering the title + + ggsave(here("Output", paste0("hist_time_disp", gsub(" ", "_", value), ".png")), plot = hist_chart, width = 6, height = 7, units = "in", dpi = 300) +} + +# Main reasons for displacement for IPS households ----------------------------- + +push_2022 <- msna_2022 %>% + select(id, q_k10, q_7_9_1) %>% + rename( + push = q_7_9_1 + ) %>% + mutate(id = id, + ones = 1, + push = ifelse(push %in% c("Insufficient/no availability of public services in last place lived (health, education, markets, WASH, etc.)", + "Other (specify)", + "Insufficient/no availability of humanitarian assistance in last place lived", + "Unacceptable living conditions (lack of water, power, sewage, privacy/overcrowding, heating, safety, etc.) in last place lived", + "Separated from my family in last place lived"), "Other", push), + push = ifelse(push == "Worse economic situation last place lived", "Worse economic situation", push), + push = ifelse(push == "Worse livelihood opportunities in last placce lived", "Worse livelihood opportunities", push), + push = ifelse(push == "Worse security situation in last place lived", "Worse security situation", push), + ) %>% + group_by(push, q_k10) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + filter(!is.na(push)) %>% + group_by(q_k10) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + +bar_chart <- ggplot(push_2022, aes(x = percentage, y = push, fill = q_k10)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Push Factor") + + scale_x_continuous(limits = c(0, max(push_2022$percentage) + (max(push_2022$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + +ggsave(here("Output", "bar_push.png"), bar_chart, width = 9, height = 6) + +# Type of shelter / housing the hh currently reside (by population type) ------- + +type_hh_2022 <- msna_2022 %>% + select(id, q_7_1, q_10_1, q_k10) %>% + mutate(ones = 1, + q_10_1 = ifelse(q_10_1 %in% c("Other (specify)", + "Substandard building (factory, farm, shop)", + "Prefabricated unit", + "Collective shelter (religious building, school, warehouse)", + "Makeshift shelter", + "Concrete block shelter", + "House/ apartment (unfinished)"), "Other", q_10_1)) + +unique_q_k10 <- unique(type_hh_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- type_hh_2022 %>% + filter(q_k10 == value) %>% + group_by(q_7_1, q_10_1) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_10_1))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_st_", gsub(" ", "_", value), ".png")), pie_chart, width = 9, height = 6) +} + +# Adequacy issues in the hh shelter -------------------------------------------- + +issues_2022 <- msna_2022 %>% + select(id, q_10_4, q_k10, q_7_1) %>% + separate( + q_10_4, + into = c("issues_1", "issues_2", "issues_3", "issues_4", "issues_5"), + sep = "; " + ) %>% + pivot_longer(cols = starts_with("issues"), names_to = "issues_q", values_to = "issues_r") %>% + filter(!is.na(issues_r)) %>% + mutate(ones = 1, + issues_r = ifelse(issues_r %in% c("Lack of electricity/ lighting (fixtures/ associated connections)", + "Lack of water (fixtures, associated connections)", + "Lack or defective sanitation (toilet, handbasin, associated connections/sewage system)"), "Lack of WASH", issues_r), + issues_r = ifelse(issues_r == "None (cannot be selected with any other option)", "None", issues_r), + issues_r = ifelse(issues_r %in% c("Lack of privacy (space/ partitions, doors)", + "Unable to lock home securely"), "Lack of privacy or security", issues_r), + issues_r = ifelse(issues_r %in% c("Leakage from roof/ ceiling", + "Windows/ doors not sealed", + "Poor facilities for persons with specific needs (PwSN) i.e. unable to access due to physical/ health condition"), "Other", issues_r), + issues_r = ifelse(issues_r == "Other (please specify)", NA, issues_r) + ) %>% + group_by(issues_r, q_k10, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(issues_r)) %>% + group_by(q_7_1, q_k10) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + +unique_q_k10 <- unique(issues_2022$q_k10) + +for (value in unique_q_k10) { + plot_data <- filter(issues_2022, q_k10 == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = issues_r, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Adequacy Issues") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("bar_issue_", gsub(" ", "_", value), ".png")), bar_chart, width = 9, height = 6) +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/B115ECF0 b/notebooks/msna/.Rproj.user/61635561/sources/per/t/B115ECF0 new file mode 100644 index 00000000..39c742e1 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/B115ECF0 @@ -0,0 +1,24 @@ +{ + "id": "B115ECF0", + "path": "C:/Users/wb607344/Downloads/syria-economic-monitor/notebooks/msna/Codes/3_4_hh_welfare.R", + "project_path": "Codes/3_4_hh_welfare.R", + "type": "r_source", + "hash": "719377186", + "contents": "", + "dirty": false, + "created": 1700687550896.0, + "source_on_save": false, + "relative_order": 7, + "properties": { + "source_window_id": "", + "Source": "Source" + }, + "folds": "", + "lastKnownWriteTime": 1700430523, + "encoding": "UTF-8", + "collab_server": "", + "source_window": "", + "last_content_update": 1700430523, + "read_only": false, + "read_only_alternatives": [] +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/B115ECF0-contents b/notebooks/msna/.Rproj.user/61635561/sources/per/t/B115ECF0-contents new file mode 100644 index 00000000..d47d42e7 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/B115ECF0-contents @@ -0,0 +1,257 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assessment +# 3_4_hh_welfare +###################################################################### + +# % of HHs by number of hours of access to electricity ------------------------- + +electr_2022 <- msna_2022 %>% + filter(!is.na(q_15_1)) %>% + mutate( + q_15_1 = ifelse(q_15_1 %in% c("16-21 hours per day", "22+ hours per day"), "16+ hours per day", q_15_1), + ) + +unique_q_k10 <- unique(wat_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- electr_2022 %>% + filter(q_k10 == value) %>% + group_by(q_7_1, q_15_1) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_15_1))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors4) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_elec_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) +} + +# % of households reporting having had sufficient water for drinking ----------- + +wat_2022 <- msna_2022 %>% + filter(!is.na(q_11_1)) %>% + mutate(q_11_1 = ifelse(q_11_1 == "Not enough water to meet any of the above needs", "No", "Yes")) + +unique_q_k10 <- unique(wat_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- wat_2022 %>% + filter(q_k10 == value) %>% + group_by(q_7_1, q_11_1) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_11_1))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_wat_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) +} + +# % of HHs by ability to meet the basic needs ---------------------------------- + +bn_2022 <- msna_2022 %>% + filter(!is.na(q_16_2)) +unique_q_k10 <- unique(bn_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- bn_2022 %>% + filter(q_k10 == value) %>% + group_by(q_7_1, q_16_2) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_16_2))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors4) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_bn_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) +} + +# Main reason limiting household’s ability to meet their basic needs ----------- + +limits_2022 <- msna_2022 %>% + select(id, q_k10, q_16_3_1, q_7_1) %>% + rename( + limit = q_16_3_1, + ) %>% + mutate(id = id, + ones = 1, + limit = ifelse(limit %in% c("Other (please specify)", + "Lack of access to services (health, education, electricity, etc.)", + "Lack of availability of services (health, education, electricity, etc.)", + "Restrictions on movement for non COVID-19 reasons (such as general insecurity, checkpoints, regulations by authorities, presence of explosive ordnance, or others)", + "Unavailability of items (medicines, bread, water, fuel, etc.)", + "Disability of one or more members in the HH", + "Issues related to lack of civil documentation", + "HH no longer receiving assistance", + "Loss of remittances"), "Other", limit) + ) %>% + filter(!is.na(limit), limit != "Prefer not to answer", limit != "No other Reasons") %>% + group_by(limit, q_k10, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + group_by(q_7_1, q_k10) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + +unique_q_k10 <- unique(safety_2022$q_k10) + +for (value in unique_q_k10) { + plot_data <- filter(limits_2022, q_k10 == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = limit, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Limitation") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("/bar_lim", gsub("/", "_", value), ".png")), bar_chart, width = 9, height = 6) +} + +# Access to healthcare --------------------------------------------------------- + +health_2022 <- msna_2022 %>% + filter(!is.na(q_9_4_1)) %>% + mutate( + health = ifelse(q_9_4_1 > 0, "Not all members got access", "All members got access") + ) %>% + select(health, q_k10, q_7_1) + +unique_q_k10 <- unique(health_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- health_2022 %>% + filter(q_k10 == value) %>% + group_by(q_7_1, health) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(health))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_health_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) +} + +# Household income over the last 3 months -------------------------------------- + +income_2022 <- msna_2022 %>% + select(q_16_4_currency, q_16_4_a, q_16_4_b, q_k10, q_16_4, q_7_1) %>% + filter(q_16_4 == "Yes") %>% + mutate(q_16_4_b = q_16_4_b/0.0071, + q_16_4_a = ifelse(q_16_4_currency == "Turkish Lira (TRY)", q_16_4_b, q_16_4_a)) # SYP to TRY on August 1, 2022 + +unique_q_k10 <- unique(income_2022$q_k10) + +for (value in unique_q_k10) { + + subset_data <- income_2022 %>% + filter(q_k10 == value) + + hist_chart <- ggplot(subset_data, aes(x = factor(q_7_1), y = q_16_4_a)) + + geom_boxplot(fill = "lightblue", color = "blue") + + labs(title = "", + x = "Population type", + y = "Syrian Pounds (SYP)") + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("box_income", gsub(" ", "_", value), ".png")), plot = hist_chart, width = 9, height = 6, units = "in", dpi = 300) + +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/DC9E5889 b/notebooks/msna/.Rproj.user/61635561/sources/per/t/DC9E5889 new file mode 100644 index 00000000..93fe4fac --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/DC9E5889 @@ -0,0 +1,24 @@ +{ + "id": "DC9E5889", + "path": "C:/Users/wb607344/Downloads/syria-economic-monitor/notebooks/msna/Codes/1_cleaning.R", + "project_path": "Codes/1_cleaning.R", + "type": "r_source", + "hash": "919943991", + "contents": "", + "dirty": false, + "created": 1700687530221.0, + "source_on_save": false, + "relative_order": 3, + "properties": { + "source_window_id": "", + "Source": "Source" + }, + "folds": "", + "lastKnownWriteTime": 1700401880, + "encoding": "UTF-8", + "collab_server": "", + "source_window": "", + "last_content_update": 1700401880, + "read_only": false, + "read_only_alternatives": [] +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/per/t/DC9E5889-contents b/notebooks/msna/.Rproj.user/61635561/sources/per/t/DC9E5889-contents new file mode 100644 index 00000000..26854a52 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/per/t/DC9E5889-contents @@ -0,0 +1,53 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assesment +# 1_cleaning +###################################################################### + +# Import raw data -------------------------------------------------------------- + +raw_2022 <- + read_xlsx( + here( + "Data", + "Raw", + "2022-09-06_SYR_MSNA2022_dataset_HHs.xlsx" + ), + sheet = "Dataset - households" + ) + +# Data quality ----------------------------------------------------------------- + +# Check missing values for each variable +#missing_values <- raw_2022 %>% +# summarise_all(~sum(is.na(.))) + +# Display missing values +#print(missing_values) + +# To see unique values and frequency +#table(raw_2022$HoH_employ) + +# Data preparation ------------------------------------------------------------- + +msna_2022 <- + raw_2022 %>% + select( + id, q_k7, q_k8, q_k9, q_k10, q_k11, q_k6, q_k12, q_r1, q_r2, q_r3, q_r12, q_r1, + q_r2, q_r3, q_r12, q_h3, q_h1, q_h2, q_8_4_1, q_16_8_b, q_8_7, q_16_8, q_16_8, + q_16_8, q_16_8, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_8_1, q_8_1_1, q_17_1, + q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_1, q_7_2, q_7_2_1, q_7_4, + q_7_6, q_7_7, q_7_9_1, q_7_9_2, q_7_9_3, q_10_1, q_10_4, q_11_1, q_10_4_e, + q_15_1, q_9_2, q_9_4, q_9_4_1, q_9_3, q_16_2, q_16_3_1, q_16_3_2, q_16_3_3, + q_16_4_currency, q_16_4_a, q_16_4_b, starts_with("q_8_1_1_"), q_16_4 + ) %>% + mutate(q_17_1 = ifelse(q_17_1 %in% c("Don't know / unsure", "Prefer not to answer"), NA, q_17_1), + q_17_3 = ifelse(q_17_3 %in% c("Don't know/unsure", "Prefer to not answer"), NA, q_17_3), + q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), + q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", + "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), + q_7_1 = ifelse(q_7_1 == "Internally displaced person (IDP)", "IDP", q_7_1), + q_7_1 = ifelse(q_7_1 == "Returnee (returned in 2022)", "Returnee (2022)", q_7_1) + ) %>% + filter(q_k10 != "Neighborhood") + \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/prop/0150AB14 b/notebooks/msna/.Rproj.user/61635561/sources/prop/0150AB14 new file mode 100644 index 00000000..bb276909 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/prop/0150AB14 @@ -0,0 +1,4 @@ +{ + "source_window_id": "", + "Source": "Source" +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/prop/5A2FCE8E b/notebooks/msna/.Rproj.user/61635561/sources/prop/5A2FCE8E new file mode 100644 index 00000000..bb276909 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/prop/5A2FCE8E @@ -0,0 +1,4 @@ +{ + "source_window_id": "", + "Source": "Source" +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/prop/99A3BEB2 b/notebooks/msna/.Rproj.user/61635561/sources/prop/99A3BEB2 new file mode 100644 index 00000000..bb276909 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/prop/99A3BEB2 @@ -0,0 +1,4 @@ +{ + "source_window_id": "", + "Source": "Source" +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/prop/9C16D759 b/notebooks/msna/.Rproj.user/61635561/sources/prop/9C16D759 new file mode 100644 index 00000000..bb276909 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/prop/9C16D759 @@ -0,0 +1,4 @@ +{ + "source_window_id": "", + "Source": "Source" +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/prop/A7EEAFB5 b/notebooks/msna/.Rproj.user/61635561/sources/prop/A7EEAFB5 new file mode 100644 index 00000000..bb276909 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/prop/A7EEAFB5 @@ -0,0 +1,4 @@ +{ + "source_window_id": "", + "Source": "Source" +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/prop/BE6B4DA0 b/notebooks/msna/.Rproj.user/61635561/sources/prop/BE6B4DA0 new file mode 100644 index 00000000..bb276909 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/prop/BE6B4DA0 @@ -0,0 +1,4 @@ +{ + "source_window_id": "", + "Source": "Source" +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/prop/FFCEA998 b/notebooks/msna/.Rproj.user/61635561/sources/prop/FFCEA998 new file mode 100644 index 00000000..5f21f510 --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/prop/FFCEA998 @@ -0,0 +1,6 @@ +{ + "source_window_id": "", + "Source": "Source", + "cursorPosition": "24,13", + "scrollLine": "20" +} \ No newline at end of file diff --git a/notebooks/msna/.Rproj.user/61635561/sources/prop/INDEX b/notebooks/msna/.Rproj.user/61635561/sources/prop/INDEX new file mode 100644 index 00000000..cb94bd8c --- /dev/null +++ b/notebooks/msna/.Rproj.user/61635561/sources/prop/INDEX @@ -0,0 +1,7 @@ +C%3A%2FUsers%2Fwb607344%2FDownloads%2Fsyria-economic-monitor%2Fnotebooks%2Fmsna%2F0_master.R="FFCEA998" +C%3A%2FUsers%2Fwb607344%2FDownloads%2Fsyria-economic-monitor%2Fnotebooks%2Fmsna%2FCodes%2F1_cleaning.R="A7EEAFB5" +C%3A%2FUsers%2Fwb607344%2FDownloads%2Fsyria-economic-monitor%2Fnotebooks%2Fmsna%2FCodes%2F2_demographics.R="BE6B4DA0" +C%3A%2FUsers%2Fwb607344%2FDownloads%2Fsyria-economic-monitor%2Fnotebooks%2Fmsna%2FCodes%2F3_1_conflict.R="0150AB14" +C%3A%2FUsers%2Fwb607344%2FDownloads%2Fsyria-economic-monitor%2Fnotebooks%2Fmsna%2FCodes%2F3_2_aid.R="5A2FCE8E" +C%3A%2FUsers%2Fwb607344%2FDownloads%2Fsyria-economic-monitor%2Fnotebooks%2Fmsna%2FCodes%2F3_3_displacement.R="9C16D759" +C%3A%2FUsers%2Fwb607344%2FDownloads%2Fsyria-economic-monitor%2Fnotebooks%2Fmsna%2FCodes%2F3_4_hh_welfare.R="99A3BEB2" diff --git a/notebooks/msna/.Rproj.user/shared/notebooks/patch-chunk-names b/notebooks/msna/.Rproj.user/shared/notebooks/patch-chunk-names new file mode 100644 index 00000000..e69de29b diff --git a/notebooks/msna/0_master.R b/notebooks/msna/0_master.R new file mode 100644 index 00000000..ef3d392a --- /dev/null +++ b/notebooks/msna/0_master.R @@ -0,0 +1,49 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assesment +# 0_master +###################################################################### + +#install.packages(c("here", "tidyverse", "visdat", "summarytools", "readxl", "ggplot2", "Hmisc", "devtools")) +#devtools::install_github("hadley/scales") + +library(here) +library(tidyverse) +library(readxl) +library(visdat) +library(summarytools) +library(ggplot2) +library(Hmisc) +library(scales) +library(dplyr) +library(viridis) +library(ggrepel) + +# Colors ----------------------------------------------------------------------- + +pie_colors <- c("#66c2e0", "#fae10b", "#fc8d62", "darkseagreen3", "lightpink1", "lightsteelblue1") +bar_colors <- c("#66c2e0", "#fae10b", "#fc8d62") + +# Codes ------------------------------------------------------------------------ + +codes <- "C:/Users/wb607344/Downloads/syria-economic-monitor/notebooks/msna/Codes" + + # Data cleaning + source(file.path(codes, "1_cleaning.R")) + + # Demographic analysis + source(file.path(codes, "2_demographics.R")) + + # Thematic pillars + + # Conflict and household welfare + source(file.path(codes, "3_1_conflict.R")) + + # Humanitarian Aid + source(file.path(codes, "3_2_aid.R")) + + # Humanitarian Aid + source(file.path(codes, "3_3_displacement.R")) + + # HH welfare + source(file.path(codes, "3_4_hh_welfare.R")) diff --git a/notebooks/msna/Codes/1_cleaning.R b/notebooks/msna/Codes/1_cleaning.R new file mode 100644 index 00000000..26854a52 --- /dev/null +++ b/notebooks/msna/Codes/1_cleaning.R @@ -0,0 +1,53 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assesment +# 1_cleaning +###################################################################### + +# Import raw data -------------------------------------------------------------- + +raw_2022 <- + read_xlsx( + here( + "Data", + "Raw", + "2022-09-06_SYR_MSNA2022_dataset_HHs.xlsx" + ), + sheet = "Dataset - households" + ) + +# Data quality ----------------------------------------------------------------- + +# Check missing values for each variable +#missing_values <- raw_2022 %>% +# summarise_all(~sum(is.na(.))) + +# Display missing values +#print(missing_values) + +# To see unique values and frequency +#table(raw_2022$HoH_employ) + +# Data preparation ------------------------------------------------------------- + +msna_2022 <- + raw_2022 %>% + select( + id, q_k7, q_k8, q_k9, q_k10, q_k11, q_k6, q_k12, q_r1, q_r2, q_r3, q_r12, q_r1, + q_r2, q_r3, q_r12, q_h3, q_h1, q_h2, q_8_4_1, q_16_8_b, q_8_7, q_16_8, q_16_8, + q_16_8, q_16_8, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_8_1, q_8_1_1, q_17_1, + q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_1, q_7_2, q_7_2_1, q_7_4, + q_7_6, q_7_7, q_7_9_1, q_7_9_2, q_7_9_3, q_10_1, q_10_4, q_11_1, q_10_4_e, + q_15_1, q_9_2, q_9_4, q_9_4_1, q_9_3, q_16_2, q_16_3_1, q_16_3_2, q_16_3_3, + q_16_4_currency, q_16_4_a, q_16_4_b, starts_with("q_8_1_1_"), q_16_4 + ) %>% + mutate(q_17_1 = ifelse(q_17_1 %in% c("Don't know / unsure", "Prefer not to answer"), NA, q_17_1), + q_17_3 = ifelse(q_17_3 %in% c("Don't know/unsure", "Prefer to not answer"), NA, q_17_3), + q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), + q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", + "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), + q_7_1 = ifelse(q_7_1 == "Internally displaced person (IDP)", "IDP", q_7_1), + q_7_1 = ifelse(q_7_1 == "Returnee (returned in 2022)", "Returnee (2022)", q_7_1) + ) %>% + filter(q_k10 != "Neighborhood") + \ No newline at end of file diff --git a/notebooks/msna/Codes/2_demographics.R b/notebooks/msna/Codes/2_demographics.R new file mode 100644 index 00000000..857f7d71 --- /dev/null +++ b/notebooks/msna/Codes/2_demographics.R @@ -0,0 +1,76 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assessment +# 2_demographics +###################################################################### + +# Population distribution ------------------------------------------------------ + + pop_2022 <- msna_2022 %>% + group_by(q_7_1, q_k9) %>% + summarise(pop = sum(q_r12, na.rm = TRUE), + .groups = 'drop') + + # Variables processing + pop_2022 <- pop_2022 %>% + mutate( + subdis_code = str_split(q_k9, " - ", simplify = TRUE)[, 1], + subdis_name = str_split(q_k9, " - ", simplify = TRUE)[, 2], + hh_pop_type = as.numeric(as.character(case_when( + q_7_1 == "Host population" ~ "1", + q_7_1 == "Internally displaced person (IDP)" ~ "2", + q_7_1 == "Returnee (returned in 2022)" ~ "3", + TRUE ~ as.character(q_7_1) + ))), + ADM3_PCODE = subdis_code, + catIDPs_new = cut(pop, breaks = c(-Inf, 0, 325, 650, 975, 1300, 1625, 1950, 2275, Inf), + labels = c("0", "1 - 325", "326 - 650", "651 - 975", "976 - 1300", "1301 - 1625", "1626 - 1950", "1951 - 2275", "2276 - 2600")) + ) %>% + select(ADM3_PCODE, subdis_code, subdis_name, hh_pop_type, pop, catIDPs_new) + + pop_2022 %>% + write_csv( + here("Data", + "Coded", + "pop_2022.csv" + ) + ) + +# HH characteristics ---------------------------------------------------- + +# # HH population type +# msna_2022$q_7_1 <- factor(msna_2022$q_7_1, levels = names(sort(table(msna_2022$q_7_1), decreasing = TRUE))) +# +# ggplot(msna_2022, aes(x = q_7_1)) + +# geom_bar(fill = "skyblue", color = "darkblue", alpha = 0.7) + +# geom_text(stat = "count", aes(label = ..count..), vjust = -0.5) + # Add labels +# labs(title = "What population type is this household?", x = "Population Type", y = "Count") + +# theme_minimal() +# +# # HH members +# ggplot(msna_2022, aes(x = q_r12)) + +# geom_histogram(binwidth = 1, fill = "skyblue", color = "darkblue", alpha = 0.7) + +# labs(title = "House hold members", x = "Age", y = "Frequency") + +# theme_minimal() + +# Respondent's demographics ---------------------------------------------------- + +# # Age +# ggplot(msna_2022, aes(y = q_r2)) + +# geom_boxplot(fill = "skyblue", color = "darkblue", alpha = 0.7) + +# labs(title = "Respondent's Age", y = "Age") + +# theme_minimal() +# +# ggplot(msna_2022, aes(x = q_r2)) + +# geom_histogram(binwidth = 2, fill = "skyblue", color = "darkblue", alpha = 0.7) + +# labs(title = "Respondent's Age", x = "Age", y = "Frequency") + +# theme_minimal() +# +# # Marital status +# msna_2022$q_r3 <- factor(msna_2022$q_r3, levels = names(sort(table(msna_2022$q_r3), decreasing = TRUE))) +# +# ggplot(msna_2022, aes(x = q_r3)) + +# geom_bar(fill = "skyblue", color = "darkblue", alpha = 0.7) + +# geom_text(stat = "count", aes(label = ..count..), vjust = -0.5) + # Add labels +# labs(title = "Respondent's Marital Status", x = "Marital Status", y = "Count") + +# theme_minimal() diff --git a/notebooks/msna/Codes/3_1_conflict.R b/notebooks/msna/Codes/3_1_conflict.R new file mode 100644 index 00000000..3b8df903 --- /dev/null +++ b/notebooks/msna/Codes/3_1_conflict.R @@ -0,0 +1,147 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assessment +# 3_1_conflict +###################################################################### + +# Presence of areas where women and girls feel unsafe -------------------------- + +unsafety_2022 <- msna_2022 %>% + group_by(q_8_7, q_k10) %>% + mutate(ones = 1) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + filter(!is.na(q_8_7), q_8_7 != "Prefer not to answer") + +unsafety_2022 <- transform(unsafety_2022, percentage = total / tapply(total, q_k10, sum)[q_k10]*100) %>% + mutate(percentage = round(percentage, 0)) + +bar_chart <- ggplot(unsafety_2022, aes(x = q_k10, y = percentage, fill = q_8_7)) + + geom_bar(stat = "identity") + + geom_text(aes(label = scales::percent(percentage, scale = 1)), # Add percentage labels + position = position_stack(vjust = 0.5), # Adjust the vertical position of labels + size = 3, # Set label size + color = "black", # Set label color + show.legend = FALSE) + + labs(title = "", + x = "Location type", + y = "Percentage of households", + fill = "") + + theme_minimal() + + coord_flip() + + theme( + legend.position = "bottom", + legend.box = "horizontal" + ) + + scale_fill_manual(values = bar_colors) + +ggsave(here("Output", "bar_unsaf_girls.png"), bar_chart, width = 10, height = 6) + +# Main safety and security concerns in the past 3 months ----------------------- + +safety_2022 <- msna_2022 %>% + select(id, q_16_8, q_k10) %>% + separate( + q_16_8, + into = c("safety_1", "safety_2", "safety_3", "safety_4", "safety_5"), + sep = "; " + ) %>% + pivot_longer(cols = starts_with("safety"), names_to = "safety_q", values_to = "safety_r") %>% + filter(!is.na(safety_r), safety_r != "Don't know/unsure", safety_r != "Prefer not to answer") %>% + mutate(ones = 1, + safety_r = ifelse(safety_r %in% c("Discrimination on the basis of race, political beliefs, religion, class, age, sex, marital status (widow/divorced), disability, etc.", + "Discrimination of any sort", + "Other (please specify)", + "Physical and logistic constraints preventing mobility (roads damaged, buildings damaged, etc.)", + "Presence of UXO, IEDs, landmines, etc. around schools", + "Tensions between host communities and returnees in areas of return", + "Safety or security concerns related to displacement", + "Safety or security concerns related to conflict, i.e. including hostilities, destruction of property, threats, HH members injured/killed", + "Threat of exploitation and abuse (including of a sexual nature) in the community", + "Exploitation due to disability", + "Presence of UXO, IEDs, landmines, etc."), + "Other", safety_r)) %>% + group_by(safety_r, q_k10) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + group_by(q_k10) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + +bar_chart <- ggplot(safety_2022, aes(x = percentage, y = safety_r, fill = q_k10)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Need") + + scale_x_continuous(limits = c(0, max(safety_2022$percentage) + (max(safety_2022$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + +ggsave(here("Output", "bar_sec.png"), bar_chart, width = 9, height = 6) + + +# High levels of stress experienced by a hh member ------------------------------ + +stress_2022 <- msna_2022 %>% + select(starts_with("q_8_5_"), q_k10, q_7_1) %>% + mutate(stress = ifelse(q_8_5_0 == "Yes" | q_8_5_1 == "Yes" | q_8_5_2 == "Yes" | q_8_5_3 == "Yes", "Yes", "No"), + stress = ifelse((q_8_5_0 == "No" & is.na(stress)) | (q_8_5_1 == "No" & is.na(stress)) | (q_8_5_2 == "No" & is.na(stress)) | (q_8_5_3 == "No" & is.na(stress)), "No", stress), + ones = 1) %>% + filter(!is.na(stress)) %>% + group_by(stress, q_k10, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') + +unique_q_k10 <- unique(stress_2022$q_k10) + +for (value in unique_q_k10) { + + subset_data <- stress_2022 %>% + filter(q_k10 == value) %>% + transform(percentage = total / tapply(total, q_7_1, sum)[q_7_1]*100) %>% + mutate(percentage = round(percentage, 0)) + + bar_chart <- ggplot(subset_data, aes(x = q_7_1, y = percentage, fill = stress)) + + geom_bar(stat = "identity") + + geom_text(aes(label = scales::percent(percentage, scale = 1)), + position = position_stack(vjust = 0.5), + size = 3, + color = "black", + show.legend = FALSE) + + labs(title = value, + x = "Population type", + y = "Percentage of households", + fill = "") + + theme_minimal() + + coord_flip() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank(), + legend.position = "bottom", + legend.box = "horizontal" + ) + + scale_fill_manual(values = bar_colors) + + ggsave(here("Output", paste0("bar_stress_", gsub(" ", "_", value), ".png")), bar_chart, width = 6, height = 6.5) + +} diff --git a/notebooks/msna/Codes/3_2_aid.R b/notebooks/msna/Codes/3_2_aid.R new file mode 100644 index 00000000..a38137f3 --- /dev/null +++ b/notebooks/msna/Codes/3_2_aid.R @@ -0,0 +1,145 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assesment +# 3_2_aid +###################################################################### + +# % HH having received aid in the 3 months ------------------------------------- + + aid_2022 <- msna_2022 %>% + group_by(q_k10, q_k9, q_7_1) %>% + summarise( + per_aid_hh_rec = mean(q_17_1 == "Yes", na.rm = TRUE) * 100, + .groups = 'drop' + ) + + aid_2022 <- aid_2022 %>% + mutate( + subdis_code = str_split(q_k9, " - ", simplify = TRUE)[, 1], + subdis_name = str_split(q_k9, " - ", simplify = TRUE)[, 2], + type_location = as.numeric(as.character(case_when( + as.character(q_k10) == "Camp" ~ "1", + as.character(q_k10) == "Community" ~ "2", + as.character(q_k10) == "Neighborhood" ~ "3", + TRUE ~ as.character(q_k10) + ))), + ADM3_PCODE = subdis_code, + catIDPs_new = cut(per_aid_hh_rec, breaks = c(-Inf, 0, 25, 50, 75, Inf), + labels = c("0%", "1% - 24%", "25% - 49%", "50% - 74%", "75% - 100%")) + ) %>% + select(ADM3_PCODE, subdis_code, subdis_name, type_location, per_aid_hh_rec, catIDPs_new) + + levels(aid_2022$type_location) <- c("Camp", "Community", "Neighborhood") + + aid_2022 %>% + write_csv( + here("Data", + "Coded", + "aid_dis_2022.csv" + ) + ) + +# Aid satisfaction ------------------------------------------------------------- + +aid_2022 <- msna_2022 %>% + filter(!is.na(q_17_3)) + +unique_q_k10 <- unique(msna_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- aid_2022 %>% + filter(q_k10 == value) %>% + group_by(q_7_1, q_17_3) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + +pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_17_3))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_aid_sat_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) +} + +# Priority needs --------------------------------------------------------------- + +needs_2022 <- msna_2022 %>% + select(id, q_7_1, q_16_1_1, q_k10) %>% + rename(need = q_16_1_1) %>% + filter(need != "All needs are met") %>% + mutate(id = id, + ones = 1, + need = ifelse(need == "Shelter assistance (emergency shelter provision, shelter repairs, rent subsidies)", "Shelter assistance", need), + need = ifelse(need %in% c("Other (specify)", + "Access to community centers and safe spaces for women and girls", + "Reintegration services", "GBV post services", + "Risk awareness and clearance (Mine Action)", + "Technical and vocational training", + "No other reasons", + "Don't know/unsure", + "Waste disposal", + "Access to safe water", + "WASH services (unloading service, toilet, handbasin, associated connections/sewage system)", + "Phone/data/communication", + "Education services", + "Electricity provision", + "Disability-specific needs (medical equipment, medicine, services)", + "Health services", "Medicine", + "Mental health and psychosocial support services (e.g. structured group activities in a safe space, invididual or group counseling, etc.)"), "Other", need), + need = ifelse(need %in% c("NFI items (e.g. clothing, blankets, cooking material, sanitation items, fuel and school equipment)", "Shelter assistance"), "Shelter assistance, NFI items", need), + need = ifelse(need %in% c("Legal advice including civil documentation and Housing, Land and Property", + "Livelihood opportunities/inability to work"), "Legal advice and documentation", need)) %>% + group_by(need, q_7_1, q_k10) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(need)) %>% + group_by(q_7_1, q_k10) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + +unique_q_k10 <- unique(safety_2022$q_k10) + +for (value in unique_q_k10) { + plot_data <- filter(needs_2022, q_k10 == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = need, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Need") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("/bar_need", gsub("/", "_", value), ".png")), bar_chart, width = 9, height = 6) +} + +# GoS-issued documentation ----------------------------------------------------- diff --git a/notebooks/msna/Codes/3_3_displacement.R b/notebooks/msna/Codes/3_3_displacement.R new file mode 100644 index 00000000..30256d9f --- /dev/null +++ b/notebooks/msna/Codes/3_3_displacement.R @@ -0,0 +1,285 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assessment +# 3_3_displacement +###################################################################### + +# If host population, have you ever been displaced? ---------------------------- +# Title: Percentage of host population households that have been displaced + +displaced_2022 <- msna_2022 %>% + filter(!is.na(q_7_2)) %>% + count(q_7_2) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(displaced_2022, aes(x = "", y = percentage, fill = fct_inorder(q_7_2))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = displaced_2022, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + ggsave(here("Output", "pie_hh_dis.png"), plot = pie_chart, width = 6, height = 6, units = "in", dpi = 300) + +# Host HHs coming back to their current location after being displaced --------- + +host_date_2022 <- msna_2022 %>% + filter(!is.na(q_7_2_1)) %>% + group_by(q_7_2_1) %>% + summarise(obs = cumsum(n())) + +time_chart <- host_date_2022 %>% + ggplot(aes(x = q_7_2_1, y = obs)) + + geom_line(color = "steelblue", size = 1.2) + + scale_y_continuous(limits = c(0, 250), expand = c(0, 0)) + + labs(title = "", + x = "Date", + y = "Households") + + theme_minimal() + + theme(axis.text.x = element_text(angle = 45, hjust = 1), + axis.title = element_text(face = "bold"), + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + panel.grid.major = element_line(color = "lightgray", linetype = "dashed"), + panel.grid.minor = element_blank(), + axis.line = element_line(color = "black")) + +ggsave(here("Output", paste0("time_host_ret", gsub(" ", "_", value), ".png")), plot = time_chart, width = 10, height = 6, units = "in", dpi = 300) + +# Where did the hh reside prior to returning to their original community ------- + +returnee_2022 <- msna_2022 %>% + filter(!is.na(q_7_4)) %>% + count(q_7_4) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(returnee_2022, aes(x = "", y = percentage, fill = fct_inorder(q_7_4))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = returnee_2022, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + ggsave(here("Output", "pie_returnee.png"), plot = pie_chart, width = 6, height = 6, units = "in", dpi = 300) + +# IDP HHs arriving to their current location ----------------------------------- + +idp_date_2022 <- msna_2022 %>% + filter(!is.na(q_7_6)) %>% + group_by(q_7_6) %>% + summarise(obs = cumsum(n())) + +time_chart <- idp_date_2022 %>% + ggplot(aes(x = q_7_6, y = obs)) + + geom_line(color = "steelblue", size = 1.2) + + scale_y_continuous(limits = c(0, 250), expand = c(0, 0)) + + labs(title = "", + x = "Date", + y = "Households") + + theme_minimal() + + theme(axis.text.x = element_text(angle = 45, hjust = 1), + axis.title = element_text(face = "bold"), + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + panel.grid.major = element_line(color = "lightgray", linetype = "dashed"), + panel.grid.minor = element_blank(), + axis.line = element_line(color = "black")) + +ggsave(here("Output", paste0("time_idp_arr", gsub(" ", "_", value), ".png")), plot = time_chart, width = 10, height = 6, units = "in", dpi = 300) + +# For IDPs, how many times have you and your HH been displaced since 2011? ----- +# Title: Times IDP households have been displaced since 2011 + +unique_q_k10 <- unique(msna_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- msna_2022 %>% + filter(!is.na(q_7_7), q_k10 == value) + + hist_chart <- ggplot(subset_data, aes(x = q_7_7)) + + geom_histogram(binwidth = 1, fill = "skyblue", color = "darkblue", alpha = 0.7) + + labs(title = value, x = "Number of Times", y = "Frequency") + + theme_minimal() + + theme(plot.title = element_text(hjust = 0.5)) # Centering the title + + ggsave(here("Output", paste0("hist_time_disp", gsub(" ", "_", value), ".png")), plot = hist_chart, width = 6, height = 7, units = "in", dpi = 300) +} + +# Main reasons for displacement for IPS households ----------------------------- + +push_2022 <- msna_2022 %>% + select(id, q_k10, q_7_9_1) %>% + rename( + push = q_7_9_1 + ) %>% + mutate(id = id, + ones = 1, + push = ifelse(push %in% c("Insufficient/no availability of public services in last place lived (health, education, markets, WASH, etc.)", + "Other (specify)", + "Insufficient/no availability of humanitarian assistance in last place lived", + "Unacceptable living conditions (lack of water, power, sewage, privacy/overcrowding, heating, safety, etc.) in last place lived", + "Separated from my family in last place lived"), "Other", push), + push = ifelse(push == "Worse economic situation last place lived", "Worse economic situation", push), + push = ifelse(push == "Worse livelihood opportunities in last placce lived", "Worse livelihood opportunities", push), + push = ifelse(push == "Worse security situation in last place lived", "Worse security situation", push), + ) %>% + group_by(push, q_k10) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + filter(!is.na(push)) %>% + group_by(q_k10) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + +bar_chart <- ggplot(push_2022, aes(x = percentage, y = push, fill = q_k10)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Push Factor") + + scale_x_continuous(limits = c(0, max(push_2022$percentage) + (max(push_2022$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + +ggsave(here("Output", "bar_push.png"), bar_chart, width = 9, height = 6) + +# Type of shelter / housing the hh currently reside (by population type) ------- + +type_hh_2022 <- msna_2022 %>% + select(id, q_7_1, q_10_1, q_k10) %>% + mutate(ones = 1, + q_10_1 = ifelse(q_10_1 %in% c("Other (specify)", + "Substandard building (factory, farm, shop)", + "Prefabricated unit", + "Collective shelter (religious building, school, warehouse)", + "Makeshift shelter", + "Concrete block shelter", + "House/ apartment (unfinished)"), "Other", q_10_1)) + +unique_q_k10 <- unique(type_hh_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- type_hh_2022 %>% + filter(q_k10 == value) %>% + group_by(q_7_1, q_10_1) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_10_1))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_st_", gsub(" ", "_", value), ".png")), pie_chart, width = 9, height = 6) +} + +# Adequacy issues in the hh shelter -------------------------------------------- + +issues_2022 <- msna_2022 %>% + select(id, q_10_4, q_k10, q_7_1) %>% + separate( + q_10_4, + into = c("issues_1", "issues_2", "issues_3", "issues_4", "issues_5"), + sep = "; " + ) %>% + pivot_longer(cols = starts_with("issues"), names_to = "issues_q", values_to = "issues_r") %>% + filter(!is.na(issues_r)) %>% + mutate(ones = 1, + issues_r = ifelse(issues_r %in% c("Lack of electricity/ lighting (fixtures/ associated connections)", + "Lack of water (fixtures, associated connections)", + "Lack or defective sanitation (toilet, handbasin, associated connections/sewage system)"), "Lack of WASH", issues_r), + issues_r = ifelse(issues_r == "None (cannot be selected with any other option)", "None", issues_r), + issues_r = ifelse(issues_r %in% c("Lack of privacy (space/ partitions, doors)", + "Unable to lock home securely"), "Lack of privacy or security", issues_r), + issues_r = ifelse(issues_r %in% c("Leakage from roof/ ceiling", + "Windows/ doors not sealed", + "Poor facilities for persons with specific needs (PwSN) i.e. unable to access due to physical/ health condition"), "Other", issues_r), + issues_r = ifelse(issues_r == "Other (please specify)", NA, issues_r) + ) %>% + group_by(issues_r, q_k10, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(issues_r)) %>% + group_by(q_7_1, q_k10) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + +unique_q_k10 <- unique(issues_2022$q_k10) + +for (value in unique_q_k10) { + plot_data <- filter(issues_2022, q_k10 == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = issues_r, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Adequacy Issues") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("bar_issue_", gsub(" ", "_", value), ".png")), bar_chart, width = 9, height = 6) +} \ No newline at end of file diff --git a/notebooks/msna/Codes/3_4_hh_welfare.R b/notebooks/msna/Codes/3_4_hh_welfare.R new file mode 100644 index 00000000..d47d42e7 --- /dev/null +++ b/notebooks/msna/Codes/3_4_hh_welfare.R @@ -0,0 +1,257 @@ +###################################################################### +# Syria Economic Monitoring +# Multi-Sectoral Needs Assessment +# 3_4_hh_welfare +###################################################################### + +# % of HHs by number of hours of access to electricity ------------------------- + +electr_2022 <- msna_2022 %>% + filter(!is.na(q_15_1)) %>% + mutate( + q_15_1 = ifelse(q_15_1 %in% c("16-21 hours per day", "22+ hours per day"), "16+ hours per day", q_15_1), + ) + +unique_q_k10 <- unique(wat_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- electr_2022 %>% + filter(q_k10 == value) %>% + group_by(q_7_1, q_15_1) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_15_1))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors4) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_elec_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) +} + +# % of households reporting having had sufficient water for drinking ----------- + +wat_2022 <- msna_2022 %>% + filter(!is.na(q_11_1)) %>% + mutate(q_11_1 = ifelse(q_11_1 == "Not enough water to meet any of the above needs", "No", "Yes")) + +unique_q_k10 <- unique(wat_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- wat_2022 %>% + filter(q_k10 == value) %>% + group_by(q_7_1, q_11_1) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_11_1))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_wat_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) +} + +# % of HHs by ability to meet the basic needs ---------------------------------- + +bn_2022 <- msna_2022 %>% + filter(!is.na(q_16_2)) +unique_q_k10 <- unique(bn_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- bn_2022 %>% + filter(q_k10 == value) %>% + group_by(q_7_1, q_16_2) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_16_2))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors4) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_bn_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) +} + +# Main reason limiting household’s ability to meet their basic needs ----------- + +limits_2022 <- msna_2022 %>% + select(id, q_k10, q_16_3_1, q_7_1) %>% + rename( + limit = q_16_3_1, + ) %>% + mutate(id = id, + ones = 1, + limit = ifelse(limit %in% c("Other (please specify)", + "Lack of access to services (health, education, electricity, etc.)", + "Lack of availability of services (health, education, electricity, etc.)", + "Restrictions on movement for non COVID-19 reasons (such as general insecurity, checkpoints, regulations by authorities, presence of explosive ordnance, or others)", + "Unavailability of items (medicines, bread, water, fuel, etc.)", + "Disability of one or more members in the HH", + "Issues related to lack of civil documentation", + "HH no longer receiving assistance", + "Loss of remittances"), "Other", limit) + ) %>% + filter(!is.na(limit), limit != "Prefer not to answer", limit != "No other Reasons") %>% + group_by(limit, q_k10, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + group_by(q_7_1, q_k10) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + +unique_q_k10 <- unique(safety_2022$q_k10) + +for (value in unique_q_k10) { + plot_data <- filter(limits_2022, q_k10 == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = limit, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Limitation") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("/bar_lim", gsub("/", "_", value), ".png")), bar_chart, width = 9, height = 6) +} + +# Access to healthcare --------------------------------------------------------- + +health_2022 <- msna_2022 %>% + filter(!is.na(q_9_4_1)) %>% + mutate( + health = ifelse(q_9_4_1 > 0, "Not all members got access", "All members got access") + ) %>% + select(health, q_k10, q_7_1) + +unique_q_k10 <- unique(health_2022$q_k10) + +for (value in unique_q_k10) { + subset_data <- health_2022 %>% + filter(q_k10 == value) %>% + group_by(q_7_1, health) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(health))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_health_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) +} + +# Household income over the last 3 months -------------------------------------- + +income_2022 <- msna_2022 %>% + select(q_16_4_currency, q_16_4_a, q_16_4_b, q_k10, q_16_4, q_7_1) %>% + filter(q_16_4 == "Yes") %>% + mutate(q_16_4_b = q_16_4_b/0.0071, + q_16_4_a = ifelse(q_16_4_currency == "Turkish Lira (TRY)", q_16_4_b, q_16_4_a)) # SYP to TRY on August 1, 2022 + +unique_q_k10 <- unique(income_2022$q_k10) + +for (value in unique_q_k10) { + + subset_data <- income_2022 %>% + filter(q_k10 == value) + + hist_chart <- ggplot(subset_data, aes(x = factor(q_7_1), y = q_16_4_a)) + + geom_boxplot(fill = "lightblue", color = "blue") + + labs(title = "", + x = "Population type", + y = "Syrian Pounds (SYP)") + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("box_income", gsub(" ", "_", value), ".png")), plot = hist_chart, width = 9, height = 6, units = "in", dpi = 300) + +} \ No newline at end of file diff --git a/notebooks/msna/Codes/3_5_maps.R b/notebooks/msna/Codes/3_5_maps.R new file mode 100644 index 00000000..4bae6ad7 --- /dev/null +++ b/notebooks/msna/Codes/3_5_maps.R @@ -0,0 +1,22 @@ +# Assuming you have loaded the necessary libraries +#install.packages(c("dplyr", "sf", "tmap")) + +library(dplyr) +library(sf) +library(tmap) +library(haven) + +# Location type +for (i in 1:3) { + + subset_data <- pop_2022 %>% filter(hh_pop_type == i) + + merged_data <- merge(subset_data, read_dta(here("Data", "Raw", "syria3.dta")), by.x = "ADM3_PCODE", by.y = "ADM3_PCODE", all.x = TRUE) + + sp_obj <- st_as_sf(merged_data, coords = c("longitude", "latitude"), crs = 4326) + + # Create map + png(here("Output", paste0("/pop_", i, ".png"))) + plot(sp_obj, col = "Reds", main = "Total population", add = TRUE) + dev.off() +} diff --git a/notebooks/msna/Codes/ado/s/spmap.ado b/notebooks/msna/Codes/ado/s/spmap.ado new file mode 100644 index 00000000..45bbc9e1 --- /dev/null +++ b/notebooks/msna/Codes/ado/s/spmap.ado @@ -0,0 +1,1604 @@ +*! -spmap-: Visualization of spatial data +*! Version 1.3.2 - 09 January 2018 - StataCorp edit for stroke align +*! Version 1.3.1 - 29 March 2017 - StataCorp edit to tempfile macros +*! Version 1.3.0 - 13 March 2017 +*! Version 1.2.0 - 14 March 2008 +*! Version 1.1.0 - 7 May 2007 +*! Version 1.0.0 - 7 December 2006 +*! Author: Maurizio Pisati +*! Department of Sociology and Social Research +*! University of Milano Bicocca (Italy) +*! maurizio.pisati@unimib.it + + + + +* ---------------------------------------------------------------------------- +* 1. Define program +* ---------------------------------------------------------------------------- + +program spmap, sortpreserve +version 9.2 + + + + +* ---------------------------------------------------------------------------- +* 2. Define syntax +* ---------------------------------------------------------------------------- + +syntax [varname(numeric default=none)] [if] [in] using/ , /// + ID(varname numeric) /// + /// + [Area(varname numeric)] /// + [SPLIT] /// + [MAP(string)] /// + [MFColor(string asis)] /// + [MOColor(string asis)] /// + [MOSize(string)] /// + [MOPattern(string asis)] /// + [MOAlign(string asis)] /// + /// + [CLMethod(name)] /// 1.3.0 Bug fix + [CLNumber(numlist max=1 >=2)] /// + [CLBreaks(numlist min=3 ascending)] /// + [EIRange(numlist min=1 max=2 sort)] /// + [KMIter(numlist max=1 >0)] /// + [NDFcolor(string asis)] /// + [NDOcolor(string asis)] /// + [NDSize(string asis)] /// + [NDPattern(string asis)] /// 1.3.0 + [NDAlign(string asis)] /// + [NDLabel(string)] /// + /// + [FColor(string asis)] /// + [OColor(string asis)] /// + [OSize(string)] /// + [OPattern(string)] /// 1.3.0 + [OAlign(string)] /// + /// + [LEGENDA(string)] /// + [LEGTitle(string asis)] /// + [LEGLabel(string)] /// + [LEGOrder(string)] /// + [LEGStyle(numlist max=1 >=0 <=3)] /// + [LEGJunction(string)] /// + [LEGCount] /// + /// + [POLygon(string asis)] /// + [LINe(string asis)] /// + [POInt(string asis)] /// + [DIAgram(string asis)] /// + [ARRow(string asis)] /// + [LABel(string asis)] /// + [SCAlebar(string asis)] /// + /// + [POLYFIRST] /// 1.2.0 + [GSize(numlist max=1 >=1)] /// 1.1.0 + [FREEstyle ] /// 1.2.0 + /// + [*] + + + + +* ---------------------------------------------------------------------------- +* 3. Check syntax +* ---------------------------------------------------------------------------- + +/* Check using file */ +if (substr(reverse("`using'"),1,4) != "atd.") local using "`using'.dta" +capture confirm file "`using'" +if _rc { + di as err "{p}File {bf:`using'} not found{p_end}" + exit 601 +} +preserve +qui use "`using'", clear +cap confirm numeric variable _ID _X _Y +if _rc { + di as err "{p}File {bf:`using'} is not a valid " /// + "{help spmap##sd_basemap:{it:basemap}} " /// + "dataset {p_end}" + exit 198 +} +restore + + +/* Check option id() */ +preserve +marksample TOUSE, novarlist +markout `TOUSE' `id' +qui keep if `TOUSE' +capture isid `id' +if _rc { + restore + di as err "{p}Variable {bf:`id'} specified in option {bf:{ul:id}()} " /// + "does not uniquely identify the observations{p_end}" + exit 459 +} +restore + + +/* Check option map() */ +if ("`area'" != "") & ("`map'" != "") { + local MAP "`map'" + if ("`MAP'" == "using") local map `"`using'"' + if (substr(reverse("`map'"),1,4) != "atd.") { + local map "`map'.dta" + } + capture confirm file "`map'" + if _rc { + di as err "{p}File {bf:`map'} specified in option " /// + "{bf:{ul:map}()} not found{p_end}" + exit 601 + } + preserve + qui use "`map'", clear + cap confirm numeric variable _ID _X _Y + if _rc { + di as err "{p}File {bf:`map'} specified in option " /// + "{bf:{ul:map}()} is not a valid " /// + "{help spmap##sd_backgroundmap:{it:backgroundmap}} " /// + "dataset {p_end}" + exit 198 + } + restore +} + + +/* Check options relevant only when attribute variable is specified */ +if ("`varlist'" != "") { + + /* Check option clmethod() */ + if ("`clmethod'" != "") { + local LIST "quantile boxplot eqint stdev kmeans custom unique" + local LEN = length("`clmethod'") + local OK = 0 + foreach W of local LIST { + if ("`clmethod'" == substr("`W'", 1, `LEN')) { + local OK = 1 + local clmethod "`W'" + continue, break + } + } + if !`OK' { + di as err "{p}Option {bf:{ul:clm}ethod()} accepts only " /// + "one of the following keywords: " /// + "{bf:{ul:q}uantile} " /// + "{bf:{ul:b}oxplot} " /// + "{bf:{ul:e}qint} " /// + "{bf:{ul:s}tdev} " /// + "{bf:{ul:k}means} " /// + "{bf:{ul:c}ustom} " /// + "{bf:{ul:u}nique} " /// + "{p_end}" + exit 198 + } + } + + /* Check option clnumber() */ + if ("`clmethod'" == "stdev") & ("`clnumber'" != "") { + if (`clnumber' > 9) { + di as err "{p}When you specify option " /// + "{bf:{ul:clm}ethod({ul:s}tdev)}, option " /// + "{bf:{ul:cln}umber()} accepts only values " /// + "between 2 and 9{p_end}" + exit 198 + } + } + + /* Check option clbreaks() */ + if ("`clmethod'" == "custom") & ("`clbreaks'" == "") { + di as err "{p}If you specify option " /// + "{bf:{ul:clm}ethod({ul:c}ustom)}, you " /// + "are requested to specify also option " /// + "{bf:{ul:clb}reaks()}{p_end}" + exit 198 + } + + /* Set clnumber */ + if ("`clmethod'" == "boxplot") { + local clnumber = 6 + } + if ("`clmethod'" == "custom") { + local NCLB : word count `clbreaks' + local clnumber = `NCLB' - 1 + } + if ("`clmethod'" == "unique") { + marksample TEMP + markout `TEMP' `id' + qui tab `varlist' if `TEMP' + local clnumber = r(r) + } + if ("`clnumber'" == "") { + local clnumber = 4 + } + + /* Check option legorder() */ + if ("`legenda'" == "") local legenda "on" + if ("`legenda'" == "on") & ("`legorder'" != "") { + local LIST "hilo lohi" + local EXIST : list posof "`legorder'" in LIST + if !`EXIST' { + di as err "{p}Option {bf:{ul:lego}rder()} accepts only one " /// + "of the following keywords: {bf:`LIST'}{p_end}" + exit 198 + } + } + +/* End condition */ +} + + +/* Check option legenda() */ +if ("`legenda'" != "") { + local LIST "on off" + local EXIST : list posof "`legenda'" in LIST + if !`EXIST' { + di as err "{p}Option {bf:{ul:legenda}()} accepts only one " /// + "of the following keywords: {bf:`LIST'}{p_end}" + exit 198 + } +} + +/* Check option leglabel() */ +if ("`legenda'" == "on") & ("`varlist'" == "") & (`"`leglabel'"' == "") { + di as err "{p}Since you have specified option " /// + "{bf:{ul:legenda}(on)} but you have not " /// + "specified any {it:attribute} variable, " /// + "you are requested to specify option " /// + "{bf:{ul:legl}abel()}{p_end}" + exit 198 +} + + + + +* ---------------------------------------------------------------------------- +* 4. Execute option area() +* ---------------------------------------------------------------------------- + +if ("`area'" != "") { + quietly { + preserve + marksample TOUSE, novarlist + markout `TOUSE' `id' `area' + count if `TOUSE' + if (r(N) == 0) error 2000 + keep if `TOUSE' + keep `id' `area' + tempvar ID V + gen `ID' = `id' + gen `V' = `area' + keep `ID' `V' + gen _ID = `ID' + keep _ID `V' + sort _ID + tempfile CTG + save `"`CTG'"', replace + if ("`MAP'" == "using") { + tempfile _ID + keep _ID + save `"`_ID'"', replace + } + use `"`using'"', clear + cap drop _ID2 + if ("`split'" == "") gen _ID2 = _ID + else { + gen _ID2 = (_X == .) + replace _ID2 = sum(_ID2) + } + sort _ID2, stable + recast double _X _Y + tempvar TEMP TEMPx TEMPy AREA CX CY + by _ID2 : gen double `TEMP' = (_X * _Y[_n+1]) - (_X[_n+1] * _Y) /// + if _n>1 & _n<_N + by _ID2 : gen double `AREA' = sum(`TEMP') + by _ID2 : replace `AREA' = `AREA'[_N] / 2 + by _ID2 : gen double `TEMPx' = (_X + _X[_n+1]) * (_X * _Y[_n+1] - /// + _X[_n+1] * _Y) if _n>1 & _n<_N + by _ID2 : gen double `CX' = sum(`TEMPx') + by _ID2 : replace `CX' = `CX'[_N] / (6 * `AREA') + by _ID2 : gen double `TEMPy' = (_Y + _Y[_n+1]) * (_X * _Y[_n+1] - /// + _X[_n+1] * _Y) if _n>1 & _n<_N + by _ID2 : gen double `CY' = sum(`TEMPy') + by _ID2 : replace `CY' = `CY'[_N] / (6 * `AREA') + replace `AREA' = abs(`AREA') + collapse `AREA' `CX' `CY', by(_ID _ID2) + merge _ID using `"`CTG'"' + keep if _merge == 3 + sort _ID _ID2 + by _ID : replace `AREA' = sum(`AREA') + by _ID : replace `AREA' = `AREA'[_N] + tempvar DENS AREA2 BETA + gen `DENS' = `V' / `AREA' + sort `DENS' + gen `AREA2' = `V' / `DENS'[_N] + gen `BETA' = sqrt(`AREA2' / `AREA') + keep _ID2 `CX' `CY' `BETA' + sort _ID2 + save `"`CTG'"', replace + use `"`using'"', clear + cap drop _ID2 _ID0 + gen _ID0 = _ID + if ("`split'" == "") gen _ID2 = _ID + else { + gen _ID2 = (_X == .) + replace _ID2 = sum(_ID2) + } + sort _ID2, stable + merge _ID2 using `"`CTG'"' + keep if _merge == 3 + cap drop __CTG_* + gen __CTG_X = `CX' + (_X - `CX') * `BETA' + gen __CTG_Y = `CY' + (_Y - `CY') * `BETA' + keep _ID0 _ID2 __CTG_* + ren _ID2 _ID + ren __CTG_X _X + ren __CTG_Y _Y + sort _ID0 _ID, stable + save `"`CTG'"', replace + if (`"`map'"' != "") { + use `"`map'"', clear + if ("`MAP'" == "using") { + merge _ID using `"`_ID'"' + keep if _merge == 3 + } + ren _X __MAP_X + ren _Y __MAP_Y + keep __MAP_* + tempfile BMAP + save `"`BMAP'"', replace + su __MAP_X + local MAP_XMIN = r(min) + local MAP_XMAX = r(max) + su __MAP_Y + local MAP_YMIN = r(min) + local MAP_YMAX = r(max) + } + restore + } +} + + + + +* ---------------------------------------------------------------------------- +* 5. Execute option polygon() +* ---------------------------------------------------------------------------- + +if (`"`polygon'"' != "") { + preserve + spmap_polygon, `polygon' + local POL_C `"`r(command)'"' + local POL_XMIN = r(xmin) + local POL_XMAX = r(xmax) + local POL_YMIN = r(ymin) + local POL_YMAX = r(ymax) + local TITLE1 `"`r(title)'"' + local KEY1 `"`r(key)'"' + local LABEL1 `"`r(label)'"' + local NK1 = r(nk) + restore +} + + + + +* ---------------------------------------------------------------------------- +* 6. Execute option line() +* ---------------------------------------------------------------------------- + +if (`"`line'"' != "") { + preserve + spmap_line, `line' + local LIN_C `"`r(command)'"' + local LIN_XMIN = r(xmin) + local LIN_XMAX = r(xmax) + local LIN_YMIN = r(ymin) + local LIN_YMAX = r(ymax) + local TITLE2 `"`r(title)'"' + local KEY2 `"`r(key)'"' + local LABEL2 `"`r(label)'"' + local NK2 = r(nk) + restore +} + + + + +* ---------------------------------------------------------------------------- +* 7. Execute option point() +* ---------------------------------------------------------------------------- + +if (`"`point'"' != "") { + preserve + spmap_point, `point' + local POI_C `"`r(command)'"' + local POI_XMIN = r(xmin) + local POI_XMAX = r(xmax) + local POI_YMIN = r(ymin) + local POI_YMAX = r(ymax) + local TITLE3 `"`r(title)'"' + local KEY3 `"`r(key)'"' + local LABEL3 `"`r(label)'"' + local NK3 = r(nk) + restore +} + + + + +* ---------------------------------------------------------------------------- +* 8. Execute option diagram() +* ---------------------------------------------------------------------------- + +if (`"`diagram'"' != "") { + preserve + spmap_diagram, `diagram' + local DIA_C `"`r(command)'"' + local DIA_XMIN = r(xmin) + local DIA_XMAX = r(xmax) + local DIA_YMIN = r(ymin) + local DIA_YMAX = r(ymax) + local TITLE4 `"`r(title)'"' + local KEY4 `"`r(key)'"' + local LABEL4 `"`r(label)'"' + local NK4 = r(nk) + restore +} + + + + +* ---------------------------------------------------------------------------- +* 9. Execute option arrow() +* ---------------------------------------------------------------------------- + +if (`"`arrow'"' != "") { + preserve + spmap_arrow, `arrow' + local ARR_C `"`r(command)'"' + local ARR_XMIN = r(xmin) + local ARR_XMAX = r(xmax) + local ARR_YMIN = r(ymin) + local ARR_YMAX = r(ymax) + local TITLE5 `"`r(title)'"' + local KEY5 `"`r(key)'"' + local LABEL5 `"`r(label)'"' + local NK5 = r(nk) + restore +} + + + + +* ---------------------------------------------------------------------------- +* 10. Execute option label() +* ---------------------------------------------------------------------------- + +if (`"`label'"' != "") { + preserve + spmap_label, `label' + local LAB_C `"`r(command)'"' + local LAB_XMIN = r(xmin) + local LAB_XMAX = r(xmax) + local LAB_YMIN = r(ymin) + local LAB_YMAX = r(ymax) + restore +} + + + + +* ---------------------------------------------------------------------------- +* 11. Define basic objects +* ---------------------------------------------------------------------------- + +/* Marksample */ +marksample TOUSE, novarlist +markout `TOUSE' `id' +qui count if `TOUSE' +if (r(N) == 0) error 2000 + +/* Preserve data */ +preserve + +/* Select relevant observations */ +qui keep if `TOUSE' + + +/* Set defaults relevant only when area() & map() != "" */ +if ("`area'" != "") & ("`map'" != "") { + + /* Set default background map fill color */ + if (`"`mfcolor'"' == "") local mfcolor "none" + + /* Set default background map outline color */ + if (`"`mocolor'"' == "") local mocolor "black" + + /* Set default background map outline size */ + if ("`mosize'" == "") local mosize "thin" + + /* Set default background map outline pattern */ + if ("`mopattern'" == "") local mopattern "solid" + + /* Set default background map outline alignment */ + if ("`moalign'" == "") local moalign "center" + +/* End */ +} + + +/* Set defaults relevant only when varlist != "" */ +if ("`varlist'" != "") { + + /* Set default classification method */ + if ("`clmethod'" == "") local clmethod "quantile" + + /* Set default kmeans iterations */ + if ("`clmethod'" == "kmeans" & "`kmiter'" == "") local kmiter = 20 + + /* Set default fill color for empty polygons */ + if (`"`ndfcolor'"' == "") local ndfcolor "white" + + /* Set default outline color for empty polygons */ + if (`"`ndocolor'"' == "") local ndocolor "black" + + /* Set default outline thickness for empty polygons */ + if (`"`ndsize'"' == "") local ndsize "thin" + + /* Set default outline pattern for empty polygons */ + if (`"`ndpattern'"' == "") local ndpattern "solid" + + /* Set default outline alignment for empty polygons */ + if (`"`ndalign'"' == "") local ndalign "center" + + /* Set default label for empty polygons */ + if (`"`ndlabel'"' == "") local ndlabel "No data" + +/* End */ +} + + +/* Set default fill color */ +local fcolor_d "none" +if (`"`fcolor'"' == "") { + if ("`varlist'" == "") local fcolor "`fcolor_d'" + else { + if ("`clmethod'" == "quantile") local fcolor "Greys" + if ("`clmethod'" == "boxplot") local fcolor "BuRd" + if ("`clmethod'" == "eqint") local fcolor "Greys" + if ("`clmethod'" == "stdev") local fcolor "BuRd" + if ("`clmethod'" == "kmeans") local fcolor "Greys" + if ("`clmethod'" == "custom") local fcolor "Greys" + if ("`clmethod'" == "unique") local fcolor "Paired" + } +} + +/* Set default outline color */ +local ocolor_d "black" +if (`"`ocolor'"' == "") local ocolor "`ocolor_d' ..." + +/* Set default outline thickness */ +local osize_d "thin" +if ("`osize'" == "") local osize "`osize_d' ..." + +/* Set default outline pattern */ +local opattern_d "solid" +if ("`opattern'" == "") local opattern "`opattern_d' ..." + +/* Set default outline alignment */ +local oalign_d "center" +if ("`oalign'" == "") local oalign "`oalign_d' ..." + + +/* Set default legend */ +if ("`legenda'" == "") { + if ("`varlist'" == "") local legenda "off" + else local legenda "on" +} + + +/* Set defaults relevant only when legenda(on) & varlist != "" */ +if ("`legenda'" == "on") & ("`varlist'" != "") { + + /* Set legend title when legtitle(varlab) */ + if (`"`legtitle'"' == "varlab") { + local legtitle : variable label `varlist' + if (`"`legtitle'"' == "") local legtitle "`varlist'" + } + + /* Set default legend order */ + if ("`legorder'" == "") { + if ("`clmethod'" == "unique") local legorder "lohi" + else local legorder "hilo" + } + + /* Set default legend style */ + if ("`legstyle'" == "") local legstyle = 1 + + /* Set default legend junction when legstyle(2) */ + if ("`legstyle'" == "2" & "`legjunction'" == "") local legjunction " - " + + /* Get attribute variable format */ + local FMT : format `varlist' + +/* End */ +} + + + + +* ---------------------------------------------------------------------------- +* 12. Create classification variable for choropleth map +* ---------------------------------------------------------------------------- + +/* Start condition */ +if ("`varlist'" != "") { + + +/* Prepare working dataset */ +keep `id' `varlist' +cap drop __CHO_* +qui clonevar __CHO_ID = `id' +qui clonevar __CHO_V = `varlist' +keep __CHO_* + +/* Define attribute range */ +su __CHO_V, meanonly +local VMIN = r(min) +local VMAX = r(max) +if ("`clmethod'" == "eqint") & ("`eirange'" != "") { + local VMIN : word 1 of `eirange' + local NI : word count `eirange' + if (`NI' == 2) local VMAX : word 2 of `eirange' +} +if ("`clmethod'" == "custom") { + local VMIN : word 1 of `clbreaks' + local VMAX : word `NCLB' of `clbreaks' +} +local VMIN = `VMIN' - 0.000001 +local VMAX = `VMAX' + 0.000001 + +/* Set number of classes */ +local NC = `clnumber' + +/* Create classification matrix */ +tempname CLASS +matrix `CLASS' = J(`NC', 4, .) +matrix colnames `CLASS' = class lower upper obs + +/* Quantile method */ +if ("`clmethod'" == "quantile") { + qui pctile _clbreaks = __CHO_V, nq(`NC') + forval i = 2/`NC' { + if (_clbreaks[`i'] == _clbreaks[`i'-1]) { + qui replace _clbreaks = . in `=`i'-1' + } + } + sort _clbreaks + qui xtile _class = __CHO_V, cutpoints(_clbreaks) + qui tab _class + if (r(r) != `NC') { + local NC = r(r) + tempname CLASS + matrix `CLASS' = J(`NC', 4, .) + matrix colnames `CLASS' = class lower upper obs + } + matrix `CLASS'[1,1] = 1 + matrix `CLASS'[1,2] = `VMIN' + matrix `CLASS'[1,3] = _clbreaks[1] + qui count if _class == 1 + matrix `CLASS'[1,4] = r(N) + forval i = 2/`=`NC'-1' { + matrix `CLASS'[`i',1] = `i' + matrix `CLASS'[`i',2] = _clbreaks[`i'-1] + matrix `CLASS'[`i',3] = _clbreaks[`i'] + qui count if _class == `i' + matrix `CLASS'[`i',4] = r(N) + } + matrix `CLASS'[`NC',1] = `NC' + matrix `CLASS'[`NC',2] = _clbreaks[`NC'-1] + matrix `CLASS'[`NC',3] = `VMAX' + qui count if _class == `NC' + matrix `CLASS'[`NC',4] = r(N) +} + +/* Boxplot method */ +if ("`clmethod'" == "boxplot") { + qui su __CHO_V, detail + local LF = r(p25) - 1.5 * (r(p75) - r(p25)) + local UF = r(p75) + 1.5 * (r(p75) - r(p25)) + if (`LF' < `VMIN') { + local VMIN = `VMIN' - 0.000001 + local LF = `VMIN' + } + if (`UF' > `VMAX') { + local VMAX = `VMAX' + 0.000001 + local UF = `VMAX' + } + local CBREAKS "`VMIN' `LF' `r(p25)' `r(p50)' `r(p75)' `UF' `VMAX'" + local IRECODE "`VMIN',`LF',`r(p25)',`r(p50)',`r(p75)',`UF',`VMAX'" + qui gen _class = irecode(__CHO_V,`IRECODE') + forval i = 1/`NC' { + matrix `CLASS'[`i',1] = `i' + matrix `CLASS'[`i',2] = `: word `i' of `CBREAKS'' + matrix `CLASS'[`i',3] = `: word `=`i'+1' of `CBREAKS'' + qui count if _class == `i' + matrix `CLASS'[`i',4] = r(N) + } +} + +/* Equal interval method */ +if ("`clmethod'" == "eqint") { + local INT = (`VMAX' - `VMIN') / `NC' + local CBREAKS "`VMIN' " + local IRECODE "`VMIN'," + forval i = 1/`=`NC'-1' { + local CB = `VMIN' + `INT' * `i' + local CBREAKS "`CBREAKS'`CB' " + local IRECODE "`IRECODE'`CB'," + } + local CBREAKS "`CBREAKS'`VMAX'" + local IRECODE "`IRECODE'`VMAX'" + qui gen _class = irecode(__CHO_V,`IRECODE') + forval i = 1/`NC' { + matrix `CLASS'[`i',1] = `i' + matrix `CLASS'[`i',2] = `: word `i' of `CBREAKS'' + matrix `CLASS'[`i',3] = `: word `=`i'+1' of `CBREAKS'' + qui count if _class == `i' + matrix `CLASS'[`i',4] = r(N) + } +} + +/* Standard deviation method */ +if ("`clmethod'"=="stdev") { + qui su __CHO_V + local VMEAN = r(mean) + local VSD = r(sd) + if (`NC' == 2) { + local CBREAKS "`VMIN' `VMEAN' `VMAX'" + local IRECODE "`VMIN',`VMEAN',`VMAX'" + } + if (`NC' > 2) { + local LIM "0.6 1.0 1.2 1.6 2.0 1.8 2.1" + local WID "1.2 1.0 0.8 0.8 0.8 0.6 0.6" + local K = `NC' - 2 + local L : word `K' of `LIM' + local W : word `K' of `WID' + numlist "-`L'(`W')`L'" + local NLIST "`r(numlist)'" + local CBREAKS "`VMIN' " + local IRECODE "`VMIN'," + forval i = 1/`=`NC'-1' { + local CB = `: word `i' of `NLIST'' * `VSD' + `VMEAN' + local CBREAKS "`CBREAKS'`CB' " + local IRECODE "`IRECODE'`CB'," + } + local CBREAKS "`CBREAKS'`VMAX'" + local IRECODE "`IRECODE'`VMAX'" + } + qui gen _class = irecode(__CHO_V,`IRECODE') + qui tab _class + if (r(N) == 0) { + di as err "{p}Problem with option {bf:{ul:clm}ethod({ul:s}tdev)} " /// + "-- Try to decrease the number of classes specified " /// + "in option {bf:{ul:cln}umber()}{p_end}" + exit 198 + } + forval i = 1/`NC' { + matrix `CLASS'[`i',1] = `i' + matrix `CLASS'[`i',2] = `: word `i' of `CBREAKS'' + matrix `CLASS'[`i',3] = `: word `=`i'+1' of `CBREAKS'' + qui count if _class == `i' + matrix `CLASS'[`i',4] = r(N) + } +} + +/* kmeans method */ +if ("`clmethod'" == "kmeans") { + qui gen _class = . + qui su __CHO_V + local SDAM = r(Var) * (r(N)-1) + local MAX = 0 + forval i = 1/`kmiter' { + qui cluster kmeans __CHO_V, k(`NC') name(__KMEANS) + local SDCM = 0 + forval j = 1/`NC' { + qui summ __CHO_V if __KMEANS == `j' + local TEMP = r(Var) * (r(N)-1) + if (`TEMP' == .) local TEMP = 0 + local SDCM = `SDCM' + `TEMP' + } + local GVF = (`SDAM' - `SDCM') / `SDAM' + if `GVF' > `MAX' { + local MAX = `GVF' + qui replace _class = __KMEANS + } + qui cluster drop _all + } + sort __CHO_V + tempvar TEMP + qui gen `TEMP' = 0 + qui replace `TEMP' = _class[_n] != _class[_n-1] + qui replace `TEMP' = sum(`TEMP') + qui replace _class = `TEMP' + forval i = 1/`NC' { + matrix `CLASS'[`i',1] = `i' + qui su __CHO_V if _class == `i' + matrix `CLASS'[`i',2] = r(min) + matrix `CLASS'[`i',3] = r(max) + matrix `CLASS'[`i',4] = r(N) + } +} + +/* Custom method */ +if ("`clmethod'" == "custom") { + local CBREAKS "`VMIN' " + local IRECODE "`VMIN'," + forval i = 2/`NC' { + local CB : word `i' of `clbreaks' + local CBREAKS "`CBREAKS'`CB' " + local IRECODE "`IRECODE'`CB'," + } + local CBREAKS "`CBREAKS'`VMAX'" + local IRECODE "`IRECODE'`VMAX'" + qui gen _class = irecode(__CHO_V,`IRECODE') + forval i = 1/`NC' { + matrix `CLASS'[`i',1] = `i' + matrix `CLASS'[`i',2] = `: word `i' of `CBREAKS'' + matrix `CLASS'[`i',3] = `: word `=`i'+1' of `CBREAKS'' + qui count if _class == `i' + matrix `CLASS'[`i',4] = r(N) + } +} + +/* Unique method */ +if ("`clmethod'" == "unique") { + matrix `CLASS' = J(`NC', 2, .) + matrix colnames `CLASS' = class obs + qui egen _class = group(__CHO_V), label lname(_class) + forval i = 1/`NC' { + matrix `CLASS'[`i',1] = `i' + qui count if _class == `i' + matrix `CLASS'[`i',2] = r(N) + } +} + +/* Create no data class */ +qui recode _class (. = 999) + +/* Create and assign class labels */ +if ("`legenda'" == "on") { + if (`legstyle' == 0) { + forval i = 1/`NC' { + if ("`legcount'" != "") { + if ("`clmethod'" != "unique") local OBS = `CLASS'[`i',4] + else local OBS = `CLASS'[`i',2] + local OBS "(`OBS')" + } + local CLAB `"`CLAB'`i' "`OBS'" "' + } + } + if (`legstyle' == 1 & "`clmethod'" != "unique") { + forval i = 1/`NC' { + local LL = `CLASS'[`i',2] + if (`i' == 1) local LL = `LL' + 0.000001 + local LL = string(`LL', "`FMT'") + if (c(dp) == "comma") local LL = subinstr("`LL'",".",",",.) + local UL = `CLASS'[`i',3] + if (`i' == `NC') local UL = `UL' - 0.000001 + local UL = string(`UL', "`FMT'") + if (c(dp) == "comma") local UL = subinstr("`UL'",".",",",.) + if ("`legcount'" != "") { + local OBS = `CLASS'[`i',4] + local OBS " (`OBS')" + } + if (`i' == 1) local CLAB `"`CLAB'`i' "[`LL',`UL']`OBS'" "' + else local CLAB `"`CLAB'`i' "(`LL',`UL']`OBS'" "' + } + } + if (`legstyle' == 2 & "`clmethod'" != "unique") { + local LJ `"`legjunction'"' + forval i = 1/`NC' { + local LL = `CLASS'[`i',2] + if (`i' == 1) local LL = `LL' + 0.000001 + local LL = string(`LL', "`FMT'") + if (c(dp) == "comma") local LL = subinstr("`LL'",".",",",.) + local UL = `CLASS'[`i',3] + if (`i' == `NC') local UL = `UL' - 0.000001 + local UL = string(`UL', "`FMT'") + if (c(dp) == "comma") local UL = subinstr("`UL'",".",",",.) + if ("`legcount'" != "") { + local OBS = `CLASS'[`i',4] + local OBS " (`OBS')" + } + local CLAB `"`CLAB'`i' "`LL'`LJ'`UL'`OBS'" "' + } + } + if (`legstyle' == 3 & "`clmethod'" != "unique") { + forval i = 1/`NC' { + local LBL "" + if (`i' == 1) local LBL = `CLASS'[`i',2] + 0.000001 + if (`i' == `NC') local LBL = `CLASS'[`i',3] - 0.000001 + if ("`LBL'" != "") { + local LBL = string(`LBL', "`FMT'") + if (c(dp) == "comma") local LBL = subinstr("`LBL'",".",",",.) + } + if ("`legcount'" != "") { + local OBS = `CLASS'[`i',4] + if ("`LBL'" != "") local OBS " (`OBS')" + else local OBS "(`OBS')" + local CLAB `"`CLAB'`i' "`LBL'`OBS'" "' + } + else local CLAB `"`CLAB'`i' "`LBL' " "' + } + } + if (`legstyle' > 0 & "`clmethod'" == "unique") { + forval i = 1/`NC' { + local LBL : label _class `i' + if ("`legcount'" != "") { + local OBS = `CLASS'[`i',2] + local OBS " (`OBS')" + } + local CLAB `"`CLAB'`i' "`LBL'`OBS' " "' + } + } + cap lab drop _class + lab def _class `CLAB', modify + lab val _class _class + qui count if _class == 999 + if r(N) > 0 { + if ("`legcount'" != "") lab def _class 999 `"`ndlabel' (`r(N)')"', add + else lab def _class 999 "`ndlabel'", add + } +} + + +/* End condition */ +} + + + + +* ---------------------------------------------------------------------------- +* 13. Parse style lists +* ---------------------------------------------------------------------------- + +/* Set max number of list items */ +if ("`varlist'" == "") local MAX = 1 +else local MAX = `NC' + +/* Set list of available color palettes */ +local PALETTE "`PALETTE' Accent Blues BrBG BuGn BuPu Dark2 GnBu Greens Greys" +local PALETTE "`PALETTE' OrRd Oranges PRGn Paired Pastel1 Pastel2 PiYG PuBu" +local PALETTE "`PALETTE' PuBuGn PuOr PuRd Purples RdBu RdGy RdPu RdYlBu" +local PALETTE "`PALETTE' RdYlGn Reds Set1 Set2 Set3 Spectral YlGn YlGnBu" +local PALETTE "`PALETTE' YlOrBr YlOrRd" +local PALETTE "`PALETTE' BuRd BuYlRd Heat Terrain Topological" +local PALETTE "`PALETTE' Blues2 Greens2 Greys2 Reds2 Rainbow" + + +/* Parse options relevant only when area() & map() != "" */ +if ("`area'" != "") & ("`map'" != "") { + + /* Parse option mfcolor() */ + local mfcolor : word 1 of `mfcolor' + + /* Parse option mocolor() */ + local mocolor : word 1 of `mocolor' + + /* Parse option mosize() */ + local mosize : word 1 of `mosize' + + /* Parse option mopattern() */ + local mopattern : word 1 of `mopattern' + + /* Parse option moalign() */ + local moalign : word 1 of `moalign' + +/* End */ +} + + +/* Parse option ndfcolor() */ +if ("`varlist'" != "") local ndfcolor : word 1 of `ndfcolor' + +/* Parse option ndocolor() */ +if ("`varlist'" != "") local ndocolor : word 1 of `ndocolor' + +/* Parse option ndsize() */ +if ("`varlist'" != "") local ndsize : word 1 of `ndsize' + +/* Parse option ndpattern() */ +if ("`varlist'" != "") local ndpattern : word 1 of `ndpattern' + +/* Parse option ndalign() */ +if ("`varlist'" != "") local ndalign : word 1 of `ndalign' + + +/* Parse option fcolor() */ +local EXIST : list posof `"`fcolor'"' in PALETTE +if `EXIST' { + if (`MAX' > 1) { + spmap_color "`fcolor'" `MAX' + local fcolor `"`s(colors)'"' + } + else { + di as err "{p}When no {it:attribute} variable is " /// + "specified, option {bf:{ul:fc}olor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`fcolor') m(`MAX') o({bf:{ul:fc}olor()}) d(`fcolor_d') + local fcolor `"`s(pl)'"' +} + +/* Parse option ocolor() */ +local EXIST : list posof `"`ocolor'"' in PALETTE +if `EXIST' { + if (`MAX' > 1) { + spmap_color "`ocolor'" `MAX' + local ocolor `"`s(colors)'"' + } + else { + di as err "{p}When no attribute {it:variable} is " /// + "specified, option {bf:{ul:oc}olor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`ocolor') m(`MAX') o({bf:{ul:oc}olor()}) d(`ocolor_d') + local ocolor `"`s(pl)'"' +} + +/* Parse option osize() */ +spmap_psl, l(`osize') m(`MAX') o({bf:{ul:os}ize()}) d(`osize_d') +local osize `"`s(pl)'"' + +/* Parse option opattern() */ +spmap_psl, l(`opattern') m(`MAX') o({bf:{ul:op}attern()}) d(`opattern_d') +local opattern `"`s(pl)'"' + +/* Parse option oalign() */ +spmap_psl, l(`oalign') m(`MAX') o({bf:{ul:oa}lign()}) d(`oalign_d') +local oalign `"`s(pl)'"' + + + + +* ---------------------------------------------------------------------------- +* 14. Prepare working dataset +* ---------------------------------------------------------------------------- + +/* No attribute variable*/ +if ("`varlist'" == "") { + quietly { + tempfile IDFILE + cap rename `id' _ID + cap drop _class + gen _class = 1 + keep _ID _class + local NC = 1 + local NODATA = 0 + if ("`area'" != "") gen _ID0 = _ID + keep _ID* _class + if ("`area'" != "") sort _ID0 _ID + else sort _ID + save `"`IDFILE'"' + if ("`area'" != "") use `"`CTG'"', clear + else use `"`using'"', clear + if ("`area'" != "") merge _ID0 using `"`IDFILE'"' + else merge _ID using `"`IDFILE'"' + keep if _merge == 3 + drop _merge + } +} + +/* Attribute variable */ +if ("`varlist'" != "") { + quietly { + tempfile IDFILE + rename __CHO_ID _ID + if ("`area'" != "") gen _ID0 = _ID + keep _ID* _class + if ("`area'" != "") sort _ID0 _ID + else sort _ID + save `"`IDFILE'"' + if ("`area'" != "") use `"`CTG'"', clear + else use `"`using'"', clear + if ("`area'" != "") merge _ID0 using `"`IDFILE'"' + else merge _ID using `"`IDFILE'"' + keep if _merge == 3 + drop _merge + count if _class == 999 + local NODATA = r(N) + } +} + + + + +* ---------------------------------------------------------------------------- +* 15. Compose main graph twoway command +* ---------------------------------------------------------------------------- + +/* Calculate x|ymin & x|ymax */ +qui su _X, meanonly +local xmin = r(min) +local xmax = r(max) +qui su _Y, meanonly +local ymin = r(min) +local ymax = r(max) +if (`"`map'"' != "") { + local xmin = min(`xmin' , `MAP_XMIN') + local xmax = max(`xmax' , `MAP_XMAX') + local ymin = min(`ymin' , `MAP_YMIN') + local ymax = max(`ymax' , `MAP_YMAX') +} +if (`"`polygon'"' != "") { + local xmin = min(`xmin' , `POL_XMIN') + local xmax = max(`xmax' , `POL_XMAX') + local ymin = min(`ymin' , `POL_YMIN') + local ymax = max(`ymax' , `POL_YMAX') +} +if (`"`line'"' != "") { + local xmin = min(`xmin' , `LIN_XMIN') + local xmax = max(`xmax' , `LIN_XMAX') + local ymin = min(`ymin' , `LIN_YMIN') + local ymax = max(`ymax' , `LIN_YMAX') +} +if (`"`point'"' != "") { + local xmin = min(`xmin' , `POI_XMIN') + local xmax = max(`xmax' , `POI_XMAX') + local ymin = min(`ymin' , `POI_YMIN') + local ymax = max(`ymax' , `POI_YMAX') +} +if (`"`diagram'"' != "") { + local xmin = min(`xmin' , `DIA_XMIN') + local xmax = max(`xmax' , `DIA_XMAX') + local ymin = min(`ymin' , `DIA_YMIN') + local ymax = max(`ymax' , `DIA_YMAX') +} +if (`"`arrow'"' != "") { + local xmin = min(`xmin' , `ARR_XMIN') + local xmax = max(`xmax' , `ARR_XMAX') + local ymin = min(`ymin' , `ARR_YMIN') + local ymax = max(`ymax' , `ARR_YMAX') +} +if (`"`label'"' != "") { + local xmin = min(`xmin' , `LAB_XMIN') + local xmax = max(`xmax' , `LAB_XMAX') + local ymin = min(`ymin' , `LAB_YMIN') + local ymax = max(`ymax' , `LAB_YMAX') +} + +/* Execute option scalebar() */ +if (`"`scalebar'"' != "") { + qui spmap_scalebar, `scalebar' xmin(`xmin') xmax(`xmax') /// + ymin(`ymin') ymax(`ymax') + local SCA_C `"`r(command)'"' + local SCA_XMIN = r(xmin) + local SCA_XMAX = r(xmax) + local SCA_YMIN = r(ymin) + local SCA_YMAX = r(ymax) + local xmin = min(`xmin' , `SCA_XMIN') + local xmax = max(`xmax' , `SCA_XMAX') + local ymin = min(`ymin' , `SCA_YMIN') + local ymax = max(`ymax' , `SCA_YMAX') +} + +/* Calculate aspect ratio of plot region*/ +local JX = (`xmax'-`xmin') * 0.01 +local JY = (`ymax' - `ymin') * 0.01 +local xmin = `xmin' - `JX' +local xmax = `xmax' + `JX' +local ymin = `ymin' - `JY' +local ymax = `ymax' + `JY' +local AR = (`ymax' - `ymin') / (`xmax' - `xmin') + +/* Set default xsize() and ysize() */ +if ("`gsize'" != "") { + if (`AR' >= 1) { + local XS = `gsize' + local YS = `AR' * `XS' + } + else { + local YS = `gsize' + local XS = (1 / `AR') * `YS' + } +} +if ("`gsize'" == "") { + if (`AR' >= 1) { + if (`AR' <= 5) local gsize = 4 + else local gsize = 20 / `AR' + local XS = `gsize' + local YS = `AR' * `XS' + } + else { + if (1 /`AR' <= 5) local gsize = 4 + else local gsize = 20 * `AR' + local YS = `gsize' + local XS = (1 / `AR') * `YS' + } +} +local XSIZE "xsize(`XS')" +local YSIZE "ysize(`YS')" + +/* Get xsize() and ysize() if specified */ +if `"`options'"' != "" { + tokenize `"`options'"' + while `"`1'"' != "" { + if (substr(`"`1'"',1,4) == "xsiz") { + local XSIZE `"`1'"' + local OPTLIST `"`OPTLIST'`1' "' + } + if (substr(`"`1'"',1,4) == "ysiz") { + local YSIZE `"`1'"' + local OPTLIST `"`OPTLIST'`1' "' + } + macro shift + } + foreach OPT of local OPTLIST { + local options : subinstr local options "`OPT'" "", all + } +} + +/* Polygon */ +if (`"`POL_C'"' != "") & ("`polyfirst'" != "") { + cap drop _merge + qui merge using "__POL.dta" + local GRAPH `"`GRAPH'`POL_C' "' +} + +/* Base map */ +if ("`area'" != "") & (`"`map'"' != "") { + cap drop _merge + qui merge using `"`BMAP'"' + local FC "`mfcolor'" + local OC "`mocolor'" + if ("`OC'" == "none") local OC "`FC'" + local OS "`mosize'" + local OP "`mopattern'" + local OA "`moalign'" + if c(stata_version) >= 15 { + local LA `"la("`OA'")"' + } + local GRAPH `"`GRAPH'(area __MAP_Y __MAP_X, nodropbase cmissing(n)"' + local GRAPH `"`GRAPH' fc("`FC'") fi(100) lc("`OC'") lw("`OS'")"' + local GRAPH `"`GRAPH' lp("`OP'") `LA') "' +} +local EMBPOL = 0 +cap confirm variable _EMBEDDED +if (_rc == 0) { + qui summ _EMBEDDED + local EMIN = r(min) + local EMAX = r(max) + qui tab _EMBEDDED + local ECAT = r(r) + if (`EMIN' == 0 & `EMAX' == 1 & `ECAT' == 2) local EMBPOL = 1 +} +if `EMBPOL' { + local FC "`ndfcolor'" + local OC "`ndocolor'" + if ("`OC'" == "none") local OC "`FC'" + local OS "`ndsize'" + local OP "`ndpattern'" + local OA "`ndalign'" + if c(stata_version) >= 15 { + local LA `"la("`OA'")"' + } + local GRAPH `"`GRAPH'(area _Y _X if _class == 999 & _EMBEDDED == 0,"' + local GRAPH `"`GRAPH' nodropbase cmissing(n) fc("`FC'") fi(100)"' + local GRAPH `"`GRAPH' lc("`OC'") lw("`OS'") lp("`OP'") `LA') "' + forval i = 1/`NC' { + local FC : word `i' of `fcolor' + local OC : word `i' of `ocolor' + if ("`OC'" == "none") local OC "`FC'" + local OS : word `i' of `osize' + local OP : word `i' of `opattern' + local OA : word `i' of `oalign' + if c(stata_version) >= 15 { + local LA `"la("`OA'")"' + } + local GRAPH `"`GRAPH'(area _Y _X if _class == `i' & _EMBEDDED == 0,"' + local GRAPH `"`GRAPH' nodropbase cmissing(n) fc("`FC'") fi(100)"' + local GRAPH `"`GRAPH' lc("`OC'") lw("`OS'") lp("`OP'") `LA') "' + } + local FC "`ndfcolor'" + local OC "`ndocolor'" + if ("`OC'" == "none") local OC "`FC'" + local OS "`ndsize'" + local OP "`ndpattern'" + local OA "`ndalign'" + if c(stata_version) >= 15 { + local LA `"la("`OA'")"' + } + local GRAPH `"`GRAPH'(area _Y _X if _class == 999 & _EMBEDDED == 1,"' + local GRAPH `"`GRAPH' nodropbase cmissing(n) fc("`FC'") fi(100)"' + local GRAPH `"`GRAPH' lc("`OC'") lw("`OS'") lp("`OP'") `LA') "' + forval i = 1/`NC' { + local FC : word `i' of `fcolor' + local OC : word `i' of `ocolor' + if ("`OC'" == "none") local OC "`FC'" + local OS : word `i' of `osize' + local OP : word `i' of `opattern' + local OA : word `i' of `oalign' + if c(stata_version) >= 15 { + local LA `"la("`OA'")"' + } + local GRAPH `"`GRAPH'(area _Y _X if _class == `i' & _EMBEDDED == 1,"' + local GRAPH `"`GRAPH' nodropbase cmissing(n) fc("`FC'") fi(100)"' + local GRAPH `"`GRAPH' lc("`OC'") lw("`OS'") lp("`OP'") `LA') "' + } +} +else { + local FC "`ndfcolor'" + local OC "`ndocolor'" + if ("`OC'" == "none") local OC "`FC'" + local OS "`ndsize'" + local OP "`ndpattern'" + local OA "`ndalign'" + if c(stata_version) >= 15 { + local LA `"la("`OA'")"' + } + local GRAPH `"`GRAPH'(area _Y _X if _class == 999, nodropbase cmissing(n)"' + local GRAPH `"`GRAPH' fc("`FC'") fi(100) lc("`OC'") lw("`OS'")"' + local GRAPH `"`GRAPH' lp("`OP'") `LA') "' + forval i = 1/`NC' { + local FC : word `i' of `fcolor' + local OC : word `i' of `ocolor' + if ("`OC'" == "none") local OC "`FC'" + local OS : word `i' of `osize' + local OP : word `i' of `opattern' + local OA : word `i' of `oalign' + if c(stata_version) >= 15 { + local LA `"la("`OA'")"' + } + local GRAPH `"`GRAPH'(area _Y _X if _class == `i', nodropbase"' + local GRAPH `"`GRAPH' cmissing(n) fc("`FC'") fi(100) lc("`OC'")"' + local GRAPH `"`GRAPH' lw("`OS'") lp("`OP'") `LA') "' + } +} + +/* Polygon */ +if (`"`POL_C'"' != "") & ("`polyfirst'" == "") { + cap drop _merge + qui merge using "__POL.dta" + local GRAPH `"`GRAPH'`POL_C' "' +} + +/* Line */ +if (`"`LIN_C'"' != "") { + cap drop _merge + qui merge using "__LIN.dta" + local GRAPH `"`GRAPH'`LIN_C' "' +} + +/* Point */ +if (`"`POI_C'"' != "") { + cap drop _merge + qui merge using "__POI.dta" + local GRAPH `"`GRAPH'`POI_C' "' +} + +/* Diagram */ +if (`"`DIA_C'"' != "") { + cap drop _merge + qui merge using "__DIA.dta" + local GRAPH `"`GRAPH'`DIA_C' "' +} + +/* Arrow */ +if (`"`ARR_C'"' != "") { + cap drop _merge + qui merge using "__ARR.dta" + local GRAPH `"`GRAPH'`ARR_C' "' +} + +/* Label */ +if (`"`LAB_C'"' != "") { + cap drop _merge + qui merge using "__LAB.dta" + local GRAPH `"`GRAPH'`LAB_C' "' +} + +/* Scalebar */ +if (`"`SCA_C'"' != "") { + local GRAPH `"`GRAPH'`SCA_C' "' +} + + + + +* ---------------------------------------------------------------------------- +* 16. Set local legend keys and labels +* ---------------------------------------------------------------------------- + +/* Set number of keys */ +local NK = `NC' + 1 +local FV = 2 +local ND = 1 +if ("`area'" != "") & (`"`map'"' != "") { + local NK = `NK' + 1 + local FV = `FV' + 1 + local ND = `ND' + 1 +} +if (`"`POL_C'"' != "") & ("`polyfirst'" != "") { + local NK = `NK' + `NK1' + local FV = `FV' + `NK1' + local ND = `ND' + `NK1' +} +local LV = `NK' +if (`NODATA' == 0) local ND "" +if `EMBPOL' local NK = `NK' + (`NC' + 1) + + +/* legenda(off) */ +if ("`legenda'" == "off") { + local TITLE "" + local KEY "" + local LABEL "" +} + + +/* legenda(on) & varlist == "" */ +if ("`legenda'" == "on") & ("`varlist'" == "") { + + /* Title */ + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + + /* Keys */ + local KEY "`FV' " + + /* Labels */ + local LABEL `"`"`leglabel'"' "' + +/* End */ +} + + +/* legenda(on) & varlist != "" */ +if ("`legenda'" == "on") & ("`varlist'" != "") { + + /* Title */ + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + + /* Keys */ + if ("`legorder'" == "hilo") numlist "`LV'/`FV'" + else numlist "`FV'/`LV'" + local KEY "`r(numlist)' " + local KEY "`KEY'`ND' " + + /* Labels */ + if ("`legorder'" == "hilo") local SEQ "`NC'(-1)1" + else local SEQ "1/`NC'" + forval i = `SEQ' { + local LBL : label (_class) `i' + local LABEL `"`LABEL'`"`LBL'"' "' + } + if (`NODATA' > 0) { + local LBL : label (_class) 999 + local LABEL `"`LABEL'`"`LBL'"' "' + } + +/* End */ +} + + + + +* ---------------------------------------------------------------------------- +* 17. Set global legend +* ---------------------------------------------------------------------------- + +/* Keys */ +local ORDER `"`TITLE' `KEY' "' +forval i = 1/5 { + if ("`NK`i''" != "") { + local ORDER `"`ORDER'`TITLE`i'' "' + foreach K in `KEY`i'' { + local V = `NK' + `K' + if (`i'==1) & ("`polyfirst'"!="") { + local V = `K' + } + local ORDER `"`ORDER'`V' "' + local KEY `"`KEY'`V' "' + } + local LABEL `"`LABEL'`LABEL`i'' "' + local NK = `NK' + `NK`i'' + if (`i'==1) & ("`polyfirst'"!="") { + local NK = `NK' + } + } +} + +/* Labels */ +local NVK : word count `KEY' +forval i = 1/`NVK' { + local K : word `i' of `KEY' + local L : word `i' of `LABEL' + local LAB `"`LAB'lab(`K' `"`L'"') "' +} + +/* Legend */ +if (trim(`"`ORDER'"') == "") local LEGEND "legend(off)" +else { + local ROWGAP "*0.50" + if ("`clmethod'" != "unique") local ROWGAP "0" + local LEGEND `"legend("' + local LEGEND `"`LEGEND' order(`ORDER') `LAB'"' + local LEGEND `"`LEGEND' symy(*0.70) symx(*0.25) keygap(*0.50)"' + local LEGEND `"`LEGEND' col(1) rowgap(`ROWGAP')"' + local LEGEND `"`LEGEND' size(*0.60)"' + local LEGEND `"`LEGEND' region(lstyle(none) fcolor(none))"' + local LEGEND `"`LEGEND' ring(0) position(7)"' + local LEGEND `"`LEGEND' )"' +} + + + + +* ---------------------------------------------------------------------------- +* 18. Draw graph +* ---------------------------------------------------------------------------- + +/* Draw graph */ +if ("`freestyle'" == "") { + graph twoway `GRAPH', `YSIZE' `XSIZE' aspect(`AR') /// + yscale(r(`ymin' `ymax') off) xscale(r(`xmin' `xmax') off) /// + ylabel(`ymin' `ymax') xlabel(`xmin' `xmax') /// + ytitle("") xtitle("") /// + `LEGEND' /// + plotregion(margin(zero) style(none)) /// + graphregion(margin(zero) style(none)) /// + scheme(s1mono) /// + `options' + } +else graph twoway `GRAPH', `LEGEND' `options' + + + + +* ---------------------------------------------------------------------------- +* 19. Housekeeping +* ---------------------------------------------------------------------------- + +if (`"`polygon'"' != "") qui erase "__POL.dta" +if (`"`line'"' != "") qui erase "__LIN.dta" +if (`"`point'"' != "") qui erase "__POI.dta" +if (`"`diagram'"' != "") qui erase "__DIA.dta" +if (`"`arrow'"' != "") qui erase "__ARR.dta" +if (`"`label'"' != "") qui erase "__LAB.dta" + + + + +* ---------------------------------------------------------------------------- +* 20. End program +* ---------------------------------------------------------------------------- + +restore +end + + + diff --git a/notebooks/msna/Codes/ado/s/spmap.hlp b/notebooks/msna/Codes/ado/s/spmap.hlp new file mode 100644 index 00000000..d9c996f3 --- /dev/null +++ b/notebooks/msna/Codes/ado/s/spmap.hlp @@ -0,0 +1,2355 @@ +{smcl} +{* 13mar2017}{...} +{cmd:help spmap}{right:Version 1.3.0} +{hline} + +{title:Title} + +{p 4 11 2} +{hi:spmap} {hline 2} Visualization of spatial data{p_end} + + +{marker syntax}{title:Syntax} + +{p 8 15 2} +{cmd:spmap} [{help spmap##choromap:{it:attribute}}] {ifin} {helpb using} +{help spmap##spatdata:{it:basemap}} +[{cmd:,} {break} +{help spmap##basemap1:{it:basemap_options}} {break} +{cmdab:pol:ygon(}{help spmap##polygon1:{it:polygon_suboptions}}{cmd:)} {break} +{cmdab:lin:e(}{help spmap##line1:{it:line_suboptions}}{cmd:)} {break} +{cmdab:poi:nt(}{help spmap##point1:{it:point_suboptions}}{cmd:)} {break} +{cmdab:dia:gram(}{help spmap##diagram1:{it:diagram_suboptions}}{cmd:)} {break} +{cmdab:arr:ow(}{help spmap##arrow1:{it:arrow_suboptions}}{cmd:)} {break} +{cmdab:lab:el(}{help spmap##label1:{it:label_suboptions}}{cmd:)} {break} +{cmdab:sca:lebar(}{help spmap##scalebar1:{it:scalebar_suboptions}}{cmd:)} + {break} +{help spmap##graph1:{it:graph_options}}] + + +{synoptset 35 tabbed}{...} +{marker basemap1}{synopthdr:{help spmap##basemap2:basemap_options}{col 41}} +{synoptline} +{syntab: Main} +{p2coldent :* {cmdab:id(}{help varname:{it:idvar}}{cmd:)}}base map + polygon identifier{p_end} + +{syntab: Cartogram} +{synopt :{cmdab:a:rea(}{help varname:{it:areavar}}{cmd:)}}draw base map + polygons with area proportional to variable {it:areavar}{p_end} +{synopt :{opt split}}split multipart base map polygons{p_end} +{synopt :{cmdab:m:ap(}{help spmap##spatdata:{it:backgroundmap}}{cmd:)}}draw + background map defined in Stata dataset {it:backgroundmap}{p_end} +{synopt :{opth mfc:olor(colorstyle)}}fill color of the + background map{p_end} +{synopt :{opth moc:olor(colorstyle)}}outline color of the + background map{p_end} +{synopt :{opth mos:ize(linewidthstyle)}}outline thickness of the + background map{p_end} +{synopt :{opth mop:attern(linepatternstyle)}}outline pattern of the + background map{p_end} + +{syntab: Choropleth map} +{synopt :{opt clm:ethod(method)}}{it:attribute} classification method, where + {it:method} is one of the following: {cmdab:q:uantile}, {cmdab:b:oxplot}, + {cmdab:e:qint}, {cmdab:s:tdev}, {cmdab:k:means}, {cmdab:c:ustom}, + {cmdab:u:nique}{p_end} +{synopt :{opt cln:umber(#)}}number of classes{p_end} +{synopt :{opth clb:reaks(numlist)}}custom class breaks{p_end} +{synopt :{opt eir:ange(min max)}}{it:attribute} range for {cmd:eqint} + classification method{p_end} +{synopt :{opt kmi:ter(#)}}number of iterations for {cmd:kmeans} + classification method{p_end} +{synopt :{opth ndf:color(colorstyle)}}fill color of empty (no data) + base map polygons{p_end} +{synopt :{opth ndo:color(colorstyle)}}outline color of empty (no data) + base map polygons{p_end} +{synopt :{opth nds:ize(linewidthstyle)}}outline thickness of empty + (no data) base map polygons{p_end} +{synopt :{opth ndp:attern(linepatternstyle)}}outline pattern of empty + (no data) base map polygons{p_end} +{synopt :{opt ndl:abel(string)}}legend label of empty (no data) + base map polygons{p_end} + +{syntab: Format} +{synopt :{cmdab:fc:olor(}{help spmap##color:{it:colorlist}}{cmd:)}}fill color + of base map polygons{p_end} +{synopt :{cmdab:oc:olor(}{help spmap##color:{it:colorlist}}{cmd:)}}outline + color of base map polygons{p_end} +{synopt :{cmdab:os:ize(}{it:{help linewidthstyle}_list}{cmd:)}}outline + thickness of base map polygons{p_end} +{synopt :{cmdab:op:attern(}{it:{help linepatternstyle}_list}{cmd:)}}outline + pattern of base map polygons{p_end} + +{syntab: Legend} +{synopt :{cmdab:legenda(on}|{cmd:off)}}display/hide base map legend{p_end} +{synopt :{opt legt:itle(string)}}base map legend title{p_end} +{synopt :{opt legl:abel(string)}}single-key base map legend label{p_end} +{synopt :{cmdab:lego:rder(hilo}|{cmd:lohi)}}base map legend order{p_end} +{synopt :{cmdab:legs:tyle(0}|{cmd:1}|{cmd:2}|{cmd:3)}}base map legend + style{p_end} +{synopt :{opt legj:unction(string)}}string connecting lower and upper class + limits in base map legend labels when {cmd:legstyle(2)}{p_end} +{synopt :{opt legc:ount}}display number of base map polygons belonging + to each class{p_end} +{synoptline} +{p 4 6 2}* Required option{p_end} + +{synoptset 35 tabbed}{...} +{marker polygon1}{synopthdr:{help spmap##polygon2:polygon_suboptions}{col 41}} +{synoptline} +{syntab: Main} +{p2coldent :* {cmdab:d:ata(}{help spmap##spatdata:{it:polygon}}{cmd:)}}Stata + dataset defining one or more supplementary polygons to be superimposed onto + the base map {p_end} +{synopt :{cmdab:s:elect(}{help drop:{it:command}}{cmd:)}}keep/drop + specified records of dataset {it:polygon}{p_end} +{synopt :{cmdab:by(}{help varname:{it:byvar_pl}}{cmd:)}}group supplementary + polygons by variable {it:byvar_pl}{p_end} + +{syntab: Format} +{synopt :{cmdab:fc:olor(}{help spmap##color:{it:colorlist}}{cmd:)}}fill color + of supplementary polygons{p_end} +{synopt :{cmdab:oc:olor(}{help spmap##color:{it:colorlist}}{cmd:)}}outline color + of supplementary polygons{p_end} +{synopt :{cmdab:os:ize(}{it:{help linewidthstyle}_list}{cmd:)}}outline thickness + of supplementary polygons{p_end} +{synopt :{cmdab:op:attern(}{it:{help linepatternstyle}_list}{cmd:)}}outline pattern + of supplementary polygons{p_end} + +{syntab: Legend} +{synopt :{cmdab:legenda(on}|{cmd:off)}}display/hide supplementary-polygon + legend{p_end} +{synopt :{opt legt:itle(string)}}supplementary-polygon legend title{p_end} +{synopt :{opt legl:abel(string)}}single-key supplementary-polygon legend + label{p_end} +{synopt :{opth legs:how(numlist)}}display only selected keys of + supplementary-polygon legend{p_end} +{synopt :{opt legc:ount}}display number of supplementary polygons belonging + to each group{p_end} +{synoptline} +{p 4 6 2}* Required when option {cmd:polygon()} is specified{p_end} + +{synoptset 35 tabbed}{...} +{marker line1}{synopthdr:{help spmap##line2:line_suboptions}{col 41}} +{synoptline} +{syntab: Main} +{p2coldent :* {cmdab:d:ata(}{help spmap##spatdata:{it:line}}{cmd:)}}Stata + dataset defining one or more polylines to be superimposed onto the + base map{p_end} +{synopt :{cmdab:s:elect(}{help drop:{it:command}}{cmd:)}}keep/drop + specified records of dataset {it:line}{p_end} +{synopt :{cmdab:by(}{help varname:{it:byvar_ln}}{cmd:)}}group polylines + by variable {it:byvar_ln}{p_end} + +{syntab: Format} +{synopt :{cmdab:co:lor(}{help spmap##color:{it:colorlist}}{cmd:)}}polyline + color{p_end} +{synopt :{cmdab:si:ze(}{it:{help linewidthstyle}_list}{cmd:)}}polyline + thickness{p_end} +{synopt :{cmdab:pa:ttern(}{it:{help linepatternstyle}_list}{cmd:)}}polyline + pattern{p_end} + +{syntab: Legend} +{synopt :{cmdab:legenda(on}|{cmd:off)}}display/hide polyline legend{p_end} +{synopt :{opt legt:itle(string)}}polyline legend title{p_end} +{synopt :{opt legl:abel(string)}}single-key polyline legend label{p_end} +{synopt :{opth legs:how(numlist)}}display only selected keys of polyline + legend{p_end} +{synopt :{opt legc:ount}}display number of polylines belonging to each + group{p_end} +{synoptline} +{p 4 6 2}* Required when option {cmd:line()} is specified{p_end} + +{synoptset 35 tabbed}{...} +{marker point1}{synopthdr:{help spmap##point2:point_suboptions}{col 41}} +{synoptline} +{syntab: Main} +{synopt :{cmdab:d:ata(}{help spmap##spatdata:{it:point}}{cmd:)}}Stata + dataset defining one or more points to be superimposed onto the + base map{p_end} +{synopt :{cmdab:s:elect(}{help drop:{it:command}}{cmd:)}}keep/drop specified + records of dataset {it:point}{p_end} +{synopt :{cmdab:by(}{help varname:{it:byvar_pn}}{cmd:)}}group points by + variable {it:byvar_pn}{p_end} +{p2coldent :* {cmdab:x:coord(}{help varname:{it:xvar_pn}}{cmd:)}}variable + containing the x-coordinate of points{p_end} +{p2coldent :* {cmdab:y:coord(}{help varname:{it:yvar_pn}}{cmd:)}}variable + containing the y-coordinate of points{p_end} + +{syntab: Proportional size} +{synopt :{cmdab:prop:ortional(}{help varname:{it:propvar_pn}}{cmd:)}}draw + point markers with size proportional to variable {it:propvar_pn}{p_end} +{synopt :{opt pr:ange(min max)}}normalization range of variable + {it:propvar_pn}{p_end} +{synopt :{cmdab:ps:ize(relative}|{cmd:absolute)}}reference system for + drawing point markers{p_end} + +{syntab: Deviation} +{synopt :{cmdab:dev:iation(}{help varname:{it:devvar_pn}}{cmd:)}}draw + point markers as deviations from given reference value of + variable {it:devvar_pn}{p_end} +{synopt :{cmdab:refv:al(}{cmd:mean}|{cmd:median}|{it:#}{cmd:)}}reference + value of variable {it:devvar_pn}{p_end} +{synopt :{cmdab:refw:eight(}{help varname:{it:weightvar_pn}}{cmd:)}}compute + reference value of variable {it:devvar_pn} weighting observations by + variable {it:weightvar_pn}{p_end} +{synopt :{opt dm:ax(#)}}absolute value of maximum deviation{p_end} + +{syntab: Format} +{synopt :{cmdab:si:ze(}{it:{help markersizestyle}_list}{cmd:)}}size of + point markers{p_end} +{synopt :{cmdab:sh:ape(}{it:{help symbolstyle}_list}{cmd:)}}shape of + point markers{p_end} +{synopt :{cmdab:fc:olor(}{help spmap##color:{it:colorlist}}{cmd:)}}fill + color of point markers{p_end} +{synopt :{cmdab:oc:olor(}{help spmap##color:{it:colorlist}}{cmd:)}}outline + color of point markers{p_end} +{synopt :{cmdab:os:ize(}{it:{help linewidthstyle}_list}{cmd:)}}outline + thickness of point markers{p_end} + +{syntab: Legend} +{synopt :{cmdab:legenda(on}|{cmd:off)}}display/hide point legend{p_end} +{synopt :{opt legt:itle(string)}}point legend title{p_end} +{synopt :{opt legl:abel(string)}}single-key point legend label{p_end} +{synopt :{opth legs:how(numlist)}}display only selected keys of point + legend{p_end} +{synopt :{opt legc:ount}}display number of points belonging to each + group{p_end} +{synoptline} +{p 4 6 2}* Required when option {cmd:point()} is specified{p_end} + +{synoptset 35 tabbed}{...} +{marker diagram1}{synopthdr:{help spmap##diagram2:diagram_suboptions}{col 41}} +{synoptline} +{syntab: Main} +{synopt :{cmdab:d:ata(}{help spmap##spatdata:{it:diagram}}{cmd:)}}Stata + dataset defining one or more diagrams to be superimposed onto the + base map at given reference points{p_end} +{synopt :{cmdab:s:elect(}{help drop:{it:command}}{cmd:)}}keep/drop specified + records of dataset {it:diagram}{p_end} +{synopt :{cmdab:by(}{help varname:{it:byvar_dg}}{cmd:)}}group diagrams by + variable {it:byvar_dg}{p_end} +{p2coldent :* {cmdab:x:coord(}{help varname:{it:xvar_dg}}{cmd:)}}variable + containing the x-coordinate of diagram reference points{p_end} +{p2coldent :* {cmdab:y:coord(}{help varname:{it:yvar_dg}}{cmd:)}}variable + containing the y-coordinate of diagram reference points{p_end} +{p2coldent :* {cmdab:v:ariables(}{help varlist:{it:diagvar_dg}}{cmd:)}}variable + or variables to be represented by diagrams{p_end} +{synopt :{cmdab:t:ype(frect}|{cmd:pie)}}diagram type{p_end} + +{syntab: Proportional size} +{synopt :{cmdab:prop:ortional(}{help varname:{it:propvar_dg}}{cmd:)}}draw + diagrams with area proportional to variable {it:propvar_dg}{p_end} +{synopt :{opt pr:ange(min max)}}reference range of variable + {it:propvar_dg}{p_end} + +{syntab: Framed-rectangle chart} +{synopt :{opt r:ange(min max)}}reference range of variable {it:diagvar_dg} + {p_end} +{synopt :{cmdab:refv:al(}{cmd:mean}|{cmd:median}|{it:#}{cmd:)}}reference value + of variable {it:diagvar_dg}{p_end} +{synopt :{cmdab:refw:eight(}{help varname:{it:weightvar_dg}}{cmd:)}}compute the + reference value of variable {it:diagvar_dg} weighting observations by + variable {it:weightvar_dg}{p_end} +{synopt :{opth refc:olor(colorstyle)}}color of the line representing the + reference value of variable {it:diagvar_dg}{p_end} +{synopt :{opth refs:ize(linewidthstyle)}}thickness of the line + representing the reference value of variable {it:diagvar_dg}{p_end} + +{syntab: Format} +{synopt :{opt si:ze(#)}}diagram size{p_end} +{synopt :{cmdab:fc:olor(}{help spmap##color:{it:colorlist}}{cmd:)}}fill + color of the diagrams{p_end} +{synopt :{cmdab:oc:olor(}{help spmap##color:{it:colorlist}}{cmd:)}}outline + color of the diagrams{p_end} +{synopt :{cmdab:os:ize(}{it:{help linewidthstyle}_list}{cmd:)}}outline + thickness of the diagrams{p_end} + +{syntab: Legend} +{synopt :{cmdab:legenda(on}|{cmd:off)}}display/hide diagram legend{p_end} +{synopt :{opt legt:itle(string)}}diagram legend title{p_end} +{synopt :{opth legs:how(numlist)}}display only selected keys of diagram + legend{p_end} +{synopt :{opt legc:ount}}display number of diagrams belonging to each + group{p_end} +{synoptline} +{p 4 6 2}* Required when option {cmd:diagram()} is specified{p_end} + +{synoptset 35 tabbed}{...} +{marker arrow1}{synopthdr:{help spmap##arrow2:arrow_suboptions}{col 41}} +{synoptline} +{syntab: Main} +{p2coldent :* {cmdab:d:ata(}{help spmap##spatdata:{it:arrow}}{cmd:)}}Stata + dataset defining one or more arrows to be superimposed onto the + base map{p_end} +{synopt :{cmdab:s:elect(}{help drop:{it:command}}{cmd:)}}keep/drop + specified records of dataset {it:arrow}{p_end} +{synopt :{cmdab:by(}{help varname:{it:byvar_ar}}{cmd:)}}group arrows by + variable {it:byvar_ar}{p_end} + +{syntab: Format} +{synopt :{opt dir:ection(directionstyle_list)}}arrow direction, where + {it:directionstyle} is one of the following: {cmd:1} (monodirectional + arrow), {cmd:2} (bidirectional arrow){p_end} +{synopt :{cmdab:hsi:ze(}{it:{help markersizestyle}_list}{cmd:)}}arrowhead + size{p_end} +{synopt :{cmdab:han:gle(}{it:{help anglestyle}_list}{cmd:)}}arrowhead + angle{p_end} +{synopt :{cmdab:hba:rbsize(}{it:{help markersizestyle}_list}{cmd:)}}size of + filled portion of arrowhead{p_end} +{synopt :{cmdab:hfc:olor(}{help spmap##color:{it:colorlist}}{cmd:)}}arrowhead + fill color{p_end} +{synopt :{cmdab:hoc:olor(}{help spmap##color:{it:colorlist}}{cmd:)}}arrowhead + outline color{p_end} +{synopt :{cmdab:hos:ize(}{it:{help linewidthstyle}_list}{cmd:)}}arrowhead + outline thickness{p_end} +{synopt :{cmdab:lco:lor(}{help spmap##color:{it:colorlist}}{cmd:)}}arrow shaft + line color{p_end} +{synopt :{cmdab:lsi:ze(}{it:{help linewidthstyle}_list}{cmd:)}}arrow shaft + line thickness{p_end} +{synopt :{cmdab:lpa:ttern(}{it:{help linepatternstyle}_list}{cmd:)}}arrow + shaft line pattern{p_end} + +{syntab: Legend} +{synopt :{cmdab:legenda(on}|{cmd:off)}}display/hide arrow legend{p_end} +{synopt :{opt legt:itle(string)}}arrow legend title{p_end} +{synopt :{opt legl:abel(string)}}single-key arrow legend label{p_end} +{synopt :{opth legs:how(numlist)}}display only selected keys of + arrow legend{p_end} +{synopt :{opt legc:ount}}display number of arrows belonging to each + group{p_end} +{synoptline} +{p 4 6 2}* Required when option {cmd:arrow()} is specified{p_end} + +{synoptset 35 tabbed}{...} +{marker label1}{synopthdr:{help spmap##label2:label_suboptions}{col 41}} +{synoptline} +{syntab: Main} +{synopt :{cmdab:d:ata(}{help spmap##spatdata:{it:label}}{cmd:)}}Stata + dataset defining one or more labels to be superimposed onto the + base map at given reference points{p_end} +{synopt :{cmdab:s:elect(}{help drop:{it:command}}{cmd:)}}keep/drop specified + records of dataset {it:label}{p_end} +{synopt :{cmdab:by(}{help varname:{it:byvar_lb}}{cmd:)}}group labels by + variable {it:byvar_lb}{p_end} +{p2coldent :* {cmdab:x:coord(}{help varname:{it:xvar_lb}}{cmd:)}}variable + containing the x-coordinate of label reference points{p_end} +{p2coldent :* {cmdab:y:coord(}{help varname:{it:yvar_lb}}{cmd:)}}variable + containing the y-coordinate of label reference points{p_end} +{p2coldent :* {cmdab:l:abel(}{help varname:{it:labvar_lb}}{cmd:)}}variable + containing the labels{p_end} + +{syntab: Format} +{synopt :{opt le:ngth(lengthstyle_list)}}maximum number of label + characters, where {it:lengthstyle} is any integer>0{p_end} +{synopt :{cmdab:si:ze(}{it:{help textsizestyle}_list}{cmd:)}}label size{p_end} +{synopt :{cmdab:co:lor(}{help spmap##color:{it:colorlist}}{cmd:)}}label color{p_end} +{synopt :{cmdab:po:sition(}{it:{help clockpos}_list}{cmd:)}}position of labels + relative to their reference point{p_end} +{synopt :{cmdab:ga:p(}{it:{help relativesize}_list}{cmd:)}}gap between labels + and their reference point{p_end} +{synopt :{cmdab:an:gle(}{it:{help anglestyle}_list}{cmd:)}}label angle{p_end} +{synoptline} +{p 4 6 2}* Required when option {cmd:label()} is specified{p_end} + +{synoptset 35 tabbed}{...} +{marker scalebar1}{synopthdr:{help spmap##scalebar2:scalebar_suboptions}{col 41}} +{synoptline} +{syntab: Main} +{p2coldent :* {opt u:nits(#)}}scale bar extent{p_end} +{synopt :{opt s:cale(#)}}ratio of scale bar units to map units{p_end} +{synopt :{opt x:pos(#)}}scale bar horizontal position relative to plot region + center{p_end} +{synopt :{opt y:pos(#)}}scale bar vertical position relative to plot region + center{p_end} + +{syntab: Format} +{synopt :{opt si:ze(#)}}scale bar height multiplier{p_end} +{synopt :{opth fc:olor(colorstyle)}}fill color of scale bar{p_end} +{synopt :{opth oc:olor(colorstyle)}}outline color of scale bar{p_end} +{synopt :{opth os:ize(linewidthstyle)}}outline thickness of scale bar{p_end} +{synopt :{opt la:bel(string)}}scale bar label{p_end} +{synopt :{opth tc:olor(colorstyle)}}color of scale bar text{p_end} +{synopt :{opth ts:ize(textsizestyle)}}size of scale bar text{p_end} +{synoptline} +{p 4 6 2}* Required when option {cmd:scalebar()} is specified{p_end} + +{synoptset 35 tabbed}{...} +{marker graph1}{synopthdr:{help spmap##graph2:graph_options}{col 41}} +{synoptline} +{syntab: Main} +{synopt :{opt polyfirst}}draw supplementary polygons before the base + map{p_end} +{synopt :{opt gs:ize(#)}}length of shortest side of {it:available area} + (in inches){p_end} +{synopt :{opt free:style}}ignore built-in graph formatting presets and + restrictions{p_end} +{synopt :{it:{help twoway_options}}}any options documented in + {bind:{bf:[G] {it:twoway_options}}}, except for + {it:aspect_option}, {it:scheme_option}, {it:by_option}, and + {it:advanced_options}{p_end} +{synoptline} + + +{marker desc}{title:Description} + +{pstd} {cmd:spmap} is aimed at visualizing several kinds of spatial data, + and is particularly suited for drawing thematic maps and displaying + the results of spatial data analyses. + +{pstd} {cmd:spmap} functioning rests on three basic principles: + +{phang2}{space 1}o{space 2}First, a base map representing a given study + region {it:R} made up of {it:N} polygons + is drawn.{p_end} + +{phang2}{space 1}o{space 2}Second, at the user's choice, one or more types + of additional spatial objects may be superimposed + onto the base map. In the current version of + {cmd:spmap}, six different types of spatial + objects can be superimposed onto the base + map: polygons (via option {cmd:polygon()}), + polylines (via option {cmd:line()}), + points (via option {cmd:point()}), + diagrams (via option {cmd:diagram()}), + arrows (via option {cmd:arrow()}), + and labels (via option {cmd:label()}).{p_end} + +{phang2}{space 1}o{space 2}Third, at the user's choice, one or more additional + map elements may be added, such as a scale bar + (via option {cmd:scalebar()}), a title, a subtitle, + a note, and a caption + (via {it:{help title_options}}).{p_end} + +{pstd}Proper specification of {cmd:spmap} options and suboptions, + combined with the availability of properly formatted spatial data, + allows the user to draw several kinds of maps, including choropleth + maps, proportional symbol maps, pin maps, pie chart maps, and + noncontiguous area cartograms. + +{pstd}While providing sensible defaults for most options and supoptions, + {cmd:spmap} gives the user full control over the formatting of almost + every map element, thus allowing the production of highly customized + maps. + + +{marker spatdata}{title:Spatial data format} + +{pstd} {cmd:spmap} requires that the spatial data to be visualized be + arranged into properly formatted Stata datasets. Such datasets + can be classified into nine + categories: {help spmap##sd_master:{it:master}}, + {help spmap##sd_basemap:{it:basemap}}, + {help spmap##sd_backgroundmap:{it:backgroundmap}}, + {help spmap##sd_polygon:{it:polygon}}, + {help spmap##sd_line:{it:line}}, + {help spmap##sd_point:{it:point}}, + {help spmap##sd_diagram:{it:diagram}}, + {help spmap##sd_arrow:{it:arrow}}, + {help spmap##sd_label:{it:label}}. + +{marker sd_master}{pstd} The {it:master} dataset is the dataset that resides + in memory when {cmd:spmap} is invoked. At the minimum, it must contain + variable {it:idvar}, a numeric variable that uniquely identifies the + polygon or polygons making up the {help spmap##desc:base map}. If a + {help spmap##choromap:choropleth map} is to be drawn, then the + {it:master} dataset should contain also variable {it:attribute}, a + numeric variable expressing the values of the feature to be + represented. Additionally, if a noncontiguous area cartogram is to be + drawn - i.e., if the polygons making up the {help spmap##desc:base map} + are to be drawn with area proportional to the values of a given numeric + variable {it:areavar} - then the {it:master} dataset should contain also + variable {it:areavar}. + +{marker sd_basemap}{pstd} A {it:basemap} dataset is a Stata dataset that + contains the definition of the polygon or polygons making up the + {help spmap##desc:base map}. A {it:basemap} dataset is required to + have the following structure: + +{center: _ID _X _Y _EMBEDDED} +{center:{hline 37}} +{center: 1 . . 0} +{center: 1 10 30 0} +{center: 1 10 50 0} +{center: 1 30 50 0} +{center: 1 30 30 0} +{center: 1 10 30 0} +{center: 2 . . 0} +{center: 2 10 10 0} +{center: 2 10 30 0} +{center: 2 18 30 0} +{center: 2 18 10 0} +{center: 2 10 10 0} +{center: 2 . . 0} +{center: 2 22 10 0} +{center: 2 22 30 0} +{center: 2 30 30 0} +{center: 2 30 10 0} +{center: 2 22 10 0} +{center: 3 . . 1} +{center: 3 15 35 1} +{center: 3 15 45 1} +{center: 3 25 45 1} +{center: 3 25 35 1} +{center: 3 15 35 1} +{center:{hline 37}} + +{pstd} _ID is required and is a numeric variable that uniquely identifies + the polygons making up the {help spmap##desc:base map}. _X is required + and is a numeric variable that contains the {it:x}-coordinate of the + nodes of the {help spmap##desc:base map} polygons. _Y is required and + is a numeric variable that contains the {it:y}-coordinate of the nodes + of the {help spmap##desc:base map} polygons. Finally, _EMBEDDED is + optional and is an indicator variable taking value 1 if the + corresponding polygon is completely enclosed in another polygon, and + value 0 otherwise. The following should be noticed: + +{phang2}{space 1}o{space 2}Both simple and multipart polygons are allowed. In + the example above, polygons 1 and 3 are simple (i.e., they consist of + a single area), while polygon 2 is multipart (i.e., it consists of two + distinct areas).{p_end} + +{phang2}{space 1}o{space 2}The first record of each simple polygon or of each + part of a multipart polygon must contain missing {it:x}- and + {it:y}-coordinates.{p_end} + +{phang2}{space 1}o{space 2}The non-missing coordinates of each simple polygon + or of each part of a multipart polygon must be ordered so as to + correspond to consecutive nodes.{p_end} + +{phang2}{space 1}o{space 2}Each simple polygon or each part of a multipart + polygon must be "closed", i.e., the last pair of non-missing coordinates + must be equal to the first pair.{p_end} + +{phang2}{space 1}o{space 2}A {it:basemap} dataset is always required to be + sorted by variable _ID.{p_end} + +{marker sd_backgroundmap}{pstd} A {it:backgroundmap} dataset is a Stata dataset + that contains the definition of the polygon or polygons making up the + background map {hline 1} a map that can be optionally drawn as + background of a noncontiguous area cartogram. A {it:backgroundmap} + dataset has exactly the same structure as a + {help spmap##sd_basemap:{it:basemap}} dataset, except for variable + _EMBEDDED that is never used. + +{marker sd_polygon}{pstd} A {it:polygon} dataset is a Stata dataset that + contains the definition of one or more supplementary polygons to + be superimposed onto the {help spmap##desc:base map}. A {it:polygon} + dataset is required to have the following structure: + +{center: _ID _X _Y {it:byvar_pl}} +{center:{hline 37}} +{center: 1 . . 1} +{center: 1 20 40 1} +{center: 1 20 42 1} +{center: 1 25 42 1} +{center: 1 25 40 1} +{center: 1 20 40 1} +{center: 2 . . 1} +{center: 2 11 20 1} +{center: 2 11 25 1} +{center: 2 13 25 1} +{center: 2 13 20 1} +{center: 2 11 20 1} +{center: 3 . . 2} +{center: 3 25 25 2} +{center: 3 25 35 2} +{center: 3 30 35 2} +{center: 3 30 25 2} +{center: 3 25 25 2} +{center:{hline 37}} + +{pstd} Variables _ID, _X, and _Y are defined exactly in the same way as in a + {help spmap##sd_basemap:{it:basemap}} dataset, with the sole exception + that only simple polygons are allowed. In turn, {it:byvar_pl} is a + placeholder denoting an optional variable that can be specified to + distinguish different kinds of supplementary polygons. + +{marker sd_line}{pstd} A {it:line} dataset is a Stata dataset that contains + the definition of one or more polylines to be superimposed onto the + {help spmap##desc:base map}. A {it:line} dataset is required to have + the following structure: + +{center: _ID _X _Y {it:byvar_ln}} +{center:{hline 37}} +{center: 1 . . 1} +{center: 1 11 30 1} +{center: 1 12 33 1} +{center: 1 15 33 1} +{center: 1 16 35 1} +{center: 1 18 40 1} +{center: 1 25 38 1} +{center: 1 25 42 1} +{center: 2 . . 2} +{center: 2 12 20 2} +{center: 2 18 15 2} +{center: 3 . . 2} +{center: 3 27 28 2} +{center: 3 27 25 2} +{center: 3 28 27 2} +{center: 3 29 25 2} +{center:{hline 37}} + +{pstd} _ID is required and is a numeric variable that uniquely identifies + the polylines. _X is required and is a numeric variable that + contains the {it:x}-coordinate of the nodes of the polylines. _Y is + required and is a numeric variable that contains the {it:y}-coordinate + of the nodes of the polylines. Finally, {it:byvar_ln} is a placeholder + denoting an optional variable that can be specified to distinguish + different kinds of polylines. The following should be noticed: + +{phang2}{space 1}o{space 2}The first record of each polyline must contain + missing {it:x}- and {it:y}-coordinates.{p_end} + +{phang2}{space 1}o{space 2}The non-missing coordinates of each polyline + must be ordered so as to correspond to consecutive nodes.{p_end} + +{marker sd_point}{pstd} A {it:point} dataset is a Stata dataset that contains + the definition of one or more points to be superimposed onto the + {help spmap##desc:base map}. A {it:point} dataset is required to have + the following structure: + +{center:{it:xvar_pn} {it:yvar_pn} {it:byvar_pn} {it:propvar_pn} {it:devvar_pn} {it:weightvar_pn}} +{center:{hline 65}} +{center: 11 30 1 100 30 1000} +{center: 20 34 1 110 25 1500} +{center: 25 40 1 90 40 1230} +{center: 25 45 2 200 10 950} +{center: 15 20 2 50 70 600} +{center:{hline 65}} + +{pstd} {it:xvar_pn} is a placeholder denoting a required numeric variable + that contains the {it:x}-coordinate of the points. {it:yvar_pn} is + a placeholder denoting a required numeric variable that contains the + {it:y}-coordinate of the points. {it:byvar_pn} is a placeholder + denoting an optional variable that can be specified to distinguish + different kinds of points. {it:propvar_pn} is a placeholder denoting + an optional variable that, when specified, requests that the point + markers be drawn with size proportional to {it:propvar_pn}. {it:devvar_pn} + is a placeholder denoting an optional variable that, when specified, + requests that the point markers be drawn as deviations from a given + reference value of {it:devvar_pn}. Finally, {it:weightvar_pn} is a + placeholder denoting an optional variable that, when specified, requests + that the reference value of {it:devvar_pn} be computed weighting + observations by variable {it:weightvar_pn}. It is important to note that + the required and optional variables making up a {it:point} dataset can + either reside in an external dataset or be part of the + {help spmap##sd_master:{it:master}} dataset. + +{marker sd_diagram}{pstd} A {it:diagram} dataset is a Stata dataset that + contains the definition of one or more diagrams to be superimposed + onto the {help spmap##desc:base map} at given reference points. A + {it:diagram} dataset is required to have the following structure: + +{center:{it:xvar_dg} {it:yvar_dg} {it:byvar_dg} {it:diagvar_dg} {it:propvar_dg} {it:weightvar_dg}} +{center:{hline 66}} +{center: 15 30 1 ... 30 1000} +{center: 18 40 1 ... 25 1500} +{center: 20 45 1 ... 40 1230} +{center: 25 45 2 ... 10 950} +{center: 15 20 2 ... 70 600} +{center:{hline 66}} + +{pstd} {it:xvar_dg} is a placeholder denoting a required numeric variable + that contains the {it:x}-coordinate of the diagram reference + points. {it:yvar_dg} is a placeholder denoting a required numeric + variable that contains the {it:y}-coordinate of the diagram reference + points. {it:byvar_dg} is a placeholder denoting an optional variable + that can be specified to distinguish different groups of + diagrams. {it:diagvar_dg} is a placeholder denoting one or more + variables to be represented by the diagrams. {it:propvar_dg} is a + placeholder denoting an optional variable that, when specified, + requests that the diagrams be drawn with area proportional to + {it:propvar_dg}. Finally, {it:weightvar_dg} is a placeholder denoting + an optional variable that, when specified, requests that the reference + value of the diagrams be computed weighting observations by variable + {it:weightvar_dg} (this applies only to framed-rectangle charts). It + is important to note that the required and optional variables making + up a {it:diagram} dataset can either reside in an external dataset or + be part of the {help spmap##sd_master:{it:master}} dataset. + +{marker sd_arrow}{pstd} An {it:arrow} dataset is a Stata dataset that contains + the definition of one or more arrows to be superimposed onto the + {help spmap##desc:base map}. An {it:arrow} dataset is required to have + the following structure: + +{center: _ID _X1 _Y1 _X2 _Y2 {it:byvar_ar}} +{center:{hline 57}} +{center: 1 11 30 18 30 1} +{center: 2 15 40 15 45 1} +{center: 3 15 40 25 40 1} +{center: 4 20 35 28 45 2} +{center: 5 17 20 20 11 2} +{center:{hline 57}} + +{pstd} _ID is required and is a numeric variable that uniquely identifies + the arrows. _X1 is required and is a numeric variable that contains + the {it:x}-coordinate of the starting point of the arrows. _Y1 is + required and is a numeric variable that contains the {it:y}-coordinate + of the starting point of the arrows. _X2 is required and is a numeric + variable that contains the {it:x}-coordinate of the ending point of + the arrows. _Y2 is required and is a numeric variable that contains + the {it:y}-coordinate of the ending point of the arrows. Finally, + {it:byvar_ar} is a placeholder denoting an optional variable that can + be specified to distinguish different kinds of arrows. + +{marker sd_label}{pstd} A {it:label} dataset is a Stata dataset that contains + the definition of one or more labels to be superimposed onto the + {help spmap##desc:base map} at given reference points. A {it:label} + dataset is required to have the following structure: + +{center:{it:xvar_lb} {it:yvar_lb} {it:byvar_lb} {it:labvar_lb}} +{center:{hline 39}} +{center: 11 33 1 Abcde} +{center: 20 37 1 Fgh} +{center: 25 43 1 IJKL} +{center: 25 48 2 Mnopqr} +{center: 15 22 2 stu} +{center:{hline 39}} + +{pstd} {it:xvar_lb} is a placeholder denoting a required numeric variable + that contains the {it:x}-coordinate of the label reference + points. {it:yvar_lb} is a placeholder denoting a required numeric + variable that contains the {it:y}-coordinate of the label reference + points. {it:byvar_lb} is a placeholder denoting an optional variable + that can be specified to distinguish different kinds of labels. Finally, + {it:labvar_lb} is a placeholder denoting the variable that contains the + labels. It is important to note that the required and optional variables + making up a {it:label} dataset can either reside in an external dataset + or be part of the {help spmap##sd_master:{it:master}} dataset. + + +{marker color}{title:Color lists} + +{pstd} Some {cmd:spmap} options and suboptions request the user to specify + a list of one or more colors. When the list includes only one color, + the user is required to specify a standard {it:{help colorstyle}}. On + the other hand, when the list includes two or more colors, the user + can either specify a standard + {help colorstyle:{it:colorstyle}} {help stylelists:{it:list}}, + or specify the name of a predefined color scheme.{p_end} + +{marker colorscheme}{pstd}The following table lists the predefined color + schemes available in the current version of {cmd:spmap}, indicating + the name of each scheme, the maximum number of different colors it + allows, its type, and its source. + +{center: NAME MAXCOL TYPE SOURCE} +{center:{hline 48}} +{center: Blues 9 Sequential Brewer} +{center: Blues2 99 Sequential Custom} +{center: BuGn 9 Sequential Brewer} +{center: BuPu 9 Sequential Brewer} +{center: GnBu 9 Sequential Brewer} +{center: Greens 9 Sequential Brewer} +{center: Greens2 99 Sequential Custom} +{center: Greys 9 Sequential Brewer} +{center: Greys2 99 Sequential Brewer} +{center: Heat 16 Sequential Custom} +{center: OrRd 9 Sequential Brewer} +{center: Oranges 9 Sequential Brewer} +{center: PuBu 9 Sequential Brewer} +{center: PuBuGn 9 Sequential Brewer} +{center: PuRd 9 Sequential Brewer} +{center: Purples 9 Sequential Brewer} +{center: Rainbow 99 Sequential Custom} +{center: RdPu 9 Sequential Brewer} +{center: Reds 9 Sequential Brewer} +{center: Reds2 99 Sequential Custom} +{center: Terrain 16 Sequential Custom} +{center:Topological 16 Sequential Custom} +{center: YlGn 9 Sequential Brewer} +{center: YlGnBu 9 Sequential Brewer} +{center: YlOrBr 9 Sequential Brewer} +{center: YlOrRd 9 Sequential Brewer} +{center: BrBG 11 Diverging Brewer} +{center: BuRd 11 Diverging Custom} +{center: BuYlRd 11 Diverging Custom} +{center: PRGn 11 Diverging Brewer} +{center: PiYG 11 Diverging Brewer} +{center: PuOr 11 Diverging Brewer} +{center: RdBu 11 Diverging Brewer} +{center: RdGy 11 Diverging Brewer} +{center: RdYlBu 11 Diverging Brewer} +{center: RdYlGn 11 Diverging Brewer} +{center: Spectral 11 Diverging Brewer} +{center: Accent 8 Qualitative Brewer} +{center: Dark2 8 Qualitative Brewer} +{center: Paired 12 Qualitative Brewer} +{center: Pastel1 9 Qualitative Brewer} +{center: Pastel2 8 Qualitative Brewer} +{center: Set1 9 Qualitative Brewer} +{center: Set2 8 Qualitative Brewer} +{center: Set3 12 Qualitative Brewer} +{center:{hline 48}} + +{pstd}Following Brewer (1999), {it:sequential schemes} are typically used to + represent ordered data, so that higher data values are represented by + darker colors; in turn, {it:diverging schemes} are used when there is + a meaningful midpoint in the data, to emphasize progressive divergence + from this midpoint in the two opposite directions; finally, + {it:qualitative schemes} are generally used to represent unordered, + categorical data. + +{pstd}The color schemes whose source is indicated as "Brewer" were designed by + Dr. Cynthia A. Brewer, Department of Geography, The Pennsylvania State + University, University Park, Pennsylvania, USA (Brewer et al. 2003). These + color schemes are used with Dr. Brewer’s permission and are taken from the + ColorBrewer map design tool available at {browse "ColorBrewer.org"}. + + +{marker choromap}{title:Choropleth maps} + +{pstd} A choropleth map can be defined as a map in which each subarea (e.g., + each census tract) of a given study region (e.g., a city) is colored + or shaded with an intensity proportional to the value taken on by a given + quantitative variable in that subarea (Slocum et al. 2005). Since + choropleth maps are one of the most popular means for representing the + spatial distribution of quantitative variables, it is worth noting the way + {cmd:spmap} can be used to draw this kind of map. + +{pstd} In {cmd:spmap}, a choropleth map is a {help spmap##desc:base map} whose + constituent polygons are colored according to the values taken on by + {it:attribute}, a numeric variable that must be contained in the + {help spmap##sd_master:{it:master}} dataset and specified immediately after + the main command (see {help spmap##syntax:syntax diagram} above). To draw + the desired choropleth map, {cmd:spmap} first groups the values taken on + by variable {it:attribute} into {it:k} classes defined by a given set + of class breaks, and then assigns a different color to each class. The + current version of {cmd:spmap} offers six methods for determining class + breaks: + +{phang2}{space 1}o{space 2}{it:Quantiles}: class breaks correspond to quantiles + of the distribution of variable {it:attribute}, so + that each class includes approximately the same + number of polygons.{p_end} + +{phang2}{space 1}o{space 2}{it:Boxplot}: the distribution of variable + {it:attribute} is divided into 6 classes defined + as follows: [min,{space 1}p25{space 1}-{space 1}1.5*iqr], + (p25{space 1}-{space 1}1.5*iqr,{space 1}p25], + (p25,{space 1}p50], (p50,{space 1}p75], + (p75,{space 1}p75{space 1}+{space 1}1.5*iqr] and + (p75{space 1}+{space 1}1.5*iqr,{space 1}max], + where iqr{space 1}={space 1}interquartile + range.{p_end} + +{phang2}{space 1}o{space 2}{it:Equal intervals}: class breaks correspond to + values that divide the distribution of variable + {it:attribute} into {it:k} equal-width + intervals.{p_end} + +{phang2}{space 1}o{space 2}{it:Standard deviates}: the distribution of + variable {it:attribute} is divided + into {it:k} classes + (2{space 1}<={space 1}{it:k}{space 1}<={space 1}9) + whose width is defined as a fraction {it:p} of its + standard deviation sd. Following the suggestions + of Evans (1977), this proportion {it:p} varies + with {it:k} as follows:{p_end} + +{center: {it:k} {it:p}} +{center:{hline 12}} +{center: 2 inf} +{center: 3 1.2} +{center: 4 1.0} +{center: 5 0.8} +{center: 6 0.8} +{center: 7 0.8} +{center: 8 0.6} +{center: 9 0.6} +{center:{hline 12}} + +{phang2}{space 1}{space 3}Class intervals are centered on the arithmetic mean + {it:m}, which is a class midpoint if {it:k} is odd + and a class boundary if {it:k} is even; the lowest + and highest classes are open-ended (Evans + 1977).{p_end} + +{phang2}{space 1}o{space 2}{it:k-means}: the distribution of variable + {it:attribute} is divided into {it:k} classes using + {help cluster kmeans:k-means partition cluster analysis}. The + clustering procedure is applied several times to + variable {it:attribute}, and the solution that + maximizes the goodness-of-variance fit (Armstrong + et al. 2003) is used. + +{phang2}{space 1}o{space 2}{it:Custom}: class breaks are specified by the user. + +{pstd} Alternatively, {cmd:spmap} allows the user to leave the values of variable + {it:attribute} ungrouped. In this case, {it:attribute} is treated as a + categorical variable and a different color is assigned to each of its values. + + +{marker basemap2}{title:Options for drawing the base map} + +{dlgtab:Main} + +{phang} +{cmdab:id(}{help varname:{it:idvar}}{cmd:)} specifies the name of a numeric + variable that uniquely identifies the polygon or polygons making up the + {help spmap##desc:base map}. {it:idvar} must be contained in the + {help spmap##sd_master:{it:master}} dataset, and its values must + correspond to the values taken on by variable _ID contained in the + {help spmap##sd_basemap:{it:basemap}} dataset. + +{dlgtab:Cartogram} + +{phang} +{cmdab:area(}{help varname:{it:areavar}}{cmd:)} requests that the polygons + making up the {help spmap##desc:base map} be drawn with area proportional + to the values taken on by numeric variable {it:areavar}, so that a + noncontiguous area cartogram (Olson 1976) is obtained. {it:areavar} must + be contained in the {help spmap##sd_master:{it:master}} dataset. + +{phang} +{cmd:split} requests that, before drawing a noncontiguous area cartogram, all + multipart {help spmap##desc:base map} polygons be split into their + constituent parts, each of which will then be treated as a distinct simple + polygon. + +{phang} +{cmdab:map(}{help spmap##sd_backgroundmap:{it:backgroundmap}}{cmd:)} requests + that, when drawing a noncontiguous area cartogram, the polygons making up + the {help spmap##desc:base map} be superimposed onto a background map + defined in Stata dataset {it:backgroundmap}. + +{phang} +{opth mfcolor(colorstyle)} specifies the fill color of the background map. The + default is {cmd:mfcolor(none)}. + +{phang} +{opth mocolor(colorstyle)} specifies the outline color of the background + map. The default is {cmd:mocolor(black)}. + +{phang} +{opth mosize(linewidthstyle)} specifies the outline thickness of the + background map. The default is {cmd:mosize(thin)}. + +{phang} +{opth mopattern(linepatternstyle)} specifies the outline pattern of the + background map. The default is {cmd:mopattern(solid)}. + +{dlgtab:Choropleth map} + +{phang} +{opt clmethod(method)} specifies the method to be used for classifying variable + {it:attribute} and representing its spatial distribution as a + {help spmap##choromap:choropleth map}. + +{phang2}{cmd:clmethod(quantile)} is the default and requests that + the quantiles method be used.{p_end} + +{phang2}{cmd:clmethod(boxplot)} requests that the boxplot + method be used.{p_end} + +{phang2}{cmd:clmethod(eqint)} requests that the equal intervals + method be used.{p_end} + +{phang2}{cmd:clmethod(stdev)} requests that the standard deviates + method be used.{p_end} + +{phang2}{cmd:clmethod(kmeans)} requests that the {it:k}-means + method be used.{p_end} + +{phang2}{cmd:clmethod(custom)} requests that class breaks be + specified by the user with option {opt clbreaks(numlist)}.{p_end} + +{phang2}{cmd:clmethod(unique)} requests that each value of variable + {it:attribute} be treated as a distinct class.{p_end} + +{phang} +{opt clnumber(#)} specifies the number of classes {it:k} in which variable + {it:attribute} is to be divided. When the quantiles, equal intervals, + standard deviates, or {it:k}-means classification method is chosen, the + default is {cmd:clnumber(4)}. When the boxplot classification method is + chosen, this option is inactive and {it:k}=6. When the custom + classification method is chosen, this option is inactive and {it:k} equals + the number of elements of {it:numlist} specified in option + {opt clbreaks(numlist)} minus 1. When the unique classification method + is chosen, this option is inactive and {it:k} equals the number of + different values taken on by variable {it:attribute}. + +{phang} +{opth clbreaks(numlist)} is required when option {cmd:clmethod(custom)} + is specified. It defines the custom class breaks to be used for classifying + variable {it:attribute}. {it:numlist} should be specified so that the + first element is the minimum value of variable {it:attribute} to be + considered; the second to {it:k}th elements are the class breaks; and the + last element is the maximum value of variable {it:attribute} to be + considered. For example, suppose we want to group the values of variable + {it:attribute} into the following four classes: [10,15], (15,20], (20,25] + and (25,50]; for this we must specify {cmd:clbreaks(10 15 20 25 50)}. + +{phang} +{opt eirange(min max)} specifies the range of values (minimum and maximum) + to be considered in the calculation of class breaks when option + {cmd:clmethod(eqint)} is specified. This option overrides the default + range [min({it:attribute}), max({it:attribute})]. + +{phang} +{opt kmiter(#)} specifies the number of times the clustering procedure is + applied when option {cmd:clmethod(kmeans)} is specified. The default + is {cmd:kmiter(20)}. + +{phang} +{opth ndfcolor(colorstyle)} specifies the fill color of the empty (no data) + polygons of the {help spmap##choromap:choropleth map}. The default is + {cmd:ndfcolor(white)}. + +{phang} +{opth ndocolor(colorstyle)} specifies the outline color of the empty (no data) + polygons of the {help spmap##choromap:choropleth map}. The default is + {cmd:ndocolor(black)}. + +{phang} +{opth ndsize(linewidthstyle)} specifies the outline thickness of the empty + (no data) polygons of the {help spmap##choromap:choropleth map}. The + default is {cmd:ndsize(thin)}. + +{phang} +{opth ndpattern(linepatternstyle)} specifies the outline pattern of the empty + (no data) polygons of the {help spmap##choromap:choropleth map}. The + default is {cmd:ndpattern(solid)}. + +{phang} +{opt ndlabel(string)} specifies the legend label to be attached to the empty + (no data) polygons of the {help spmap##choromap:choropleth map}. The + default is {cmd:ndlabel(No data)}. + +{dlgtab:Format} + +{phang} +{cmdab:fcolor(}{help spmap##color:{it:colorlist}}{cmd:)} specifies the + list of fill colors of the {help spmap##desc:base map} polygons. When + no {help spmap##choromap:choropleth map} is drawn, the list should + include only one element. On the other hand, when a + {help spmap##choromap:choropleth map} is drawn, the list should + be either composed of {it:k} elements, or represented by the name + of a predefined {help spmap##colorscheme:color scheme}. The default + fill color is {cmd:none}. When a {help spmap##choromap:choropleth map} + is drawn, the default argument is a {help spmap##colorscheme:color scheme} + that depends on the classification method specified in option + {opt clmethod(method)}: + +{center:Classification Default } +{center: method color scheme } +{center:{hline 34}} +{center: quantile Greys } +{center: boxplot BuRd } +{center: eqint Greys } +{center: stdev BuRd } +{center: kmeans Greys } +{center: custom Greys } +{center: unique Paired } +{center:{hline 34}} + +{phang} +{cmdab:ocolor(}{help spmap##color:{it:colorlist}}{cmd:)} specifies the + list of outline colors of the {help spmap##desc:base map} polygons. When + no {help spmap##choromap:choropleth map} is drawn, the list should + include only one element. On the other hand, when a + {help spmap##choromap:choropleth map} is drawn, the list should + be either composed of {it:k} elements, or represented by the name + of a predefined {help spmap##colorscheme:color scheme}. The default + outline color is {cmd:black}, the default specification is + {cmd:ocolor(black ...)}. + +{phang} +{cmdab:osize(}{it:{help linewidthstyle}_list}{cmd:)} specifies the + {help stylelists:list} of outline thicknesses of the + {help spmap##desc:base map} polygons. When no + {help spmap##choromap:choropleth map} is drawn, the list should + include only one element. On the other hand, when a + {help spmap##choromap:choropleth map} is drawn, the list should + be composed of {it:k} elements. The default outline thickness is + {cmd:thin}, the default specification is {cmd:osize(thin ...)}. + +{phang} +{cmdab:opattern(}{it:{help linepatternstyle}_list}{cmd:)} specifies the + {help stylelists:list} of outline patterns of the + {help spmap##desc:base map} polygons. When no + {help spmap##choromap:choropleth map} is drawn, the list should + include only one element. On the other hand, when a + {help spmap##choromap:choropleth map} is drawn, the list should + be composed of {it:k} elements. The default outline pattern is + {cmd:solid}, the default specification is {cmd:opattern(solid ...)}. + +{dlgtab:Legend} + +{phang} +{cmdab:legenda(on}|{cmd:off)} specifies whether the {help spmap##desc:base map} + legend should be displayed or hidden. + +{phang2}{cmd:legenda(on)} requests that the {help spmap##desc:base map} legend + be displayed. This is the default when a + {help spmap##choromap:choropleth map} is drawn.{p_end} + +{phang2}{cmd:legenda(off)} requests that the {help spmap##desc:base map} legend + be hidden. This is the default when no {help spmap##choromap:choropleth map} + is drawn.{p_end} + +{phang} +{opt legtitle(string)} specifies the title of the {help spmap##desc:base map} + legend. When a {help spmap##choromap:choropleth map} is drawn, option + {cmd:legtitle(varlab)} requests that the label of variable {it:attribute} + be used as the legend title. + +{phang} +{opt leglabel(string)} specifies the label to be attached to the single key of + the {help spmap##desc:base map} legend when no + {help spmap##choromap:choropleth map} is drawn. This option is required when + option {cmd:legenda(on)} is specified and no + {help spmap##choromap:choropleth map} is drawn. + +{phang} +{cmdab:legorder(hilo}|{cmd:lohi)} specifies the display order of the keys of + the {help spmap##desc:base map} legend when a + {help spmap##choromap:choropleth map} is drawn. + +{phang2}{cmd:legorder(hilo)} is the default and requests that the keys of the + {help spmap##desc:base map} legend be displayed in descending order of + variable {it:attribute}.{p_end} + +{phang2}{cmd:legorder(lohi)} requests that the keys of the + {help spmap##desc:base map} legend be displayed in ascending order of + variable {it:attribute}. This is the default when option + {cmd:clmethod({cmdab:u:nique})} is specified.{p_end} + +{phang} +{cmdab:legstyle(0}|{cmd:1}|{cmd:2}|{cmd:3)} specifies the way the keys of + the {help spmap##desc:base map} legend are labelled when a + {help spmap##choromap:choropleth map} is drawn. + +{phang2}{cmd:legstyle(0)} requests that the keys of the + {help spmap##desc:base map} legend not be labelled.{p_end} + +{phang2}{cmd:legstyle(1)} is the default and requests that the keys of the + {help spmap##desc:base map} legend be labelled using the standard + mathematical notation for value intervals (e.g.: (20,35]).{p_end} + +{phang2}{cmd:legstyle(2)} requests that the keys of the + {help spmap##desc:base map} legend be labelled using the notation + ll&ul, where ll denotes the lower limit of the class interval, ul + denotes the upper limit of the class interval, and & denotes a + string that separates the two values. For example, if ll=20, ul=35, + and &=" - ", then the resulting label will be "20 - 35".{p_end} + +{phang2}{cmd:legstyle(3)} requests that only the first and last keys of + the {help spmap##desc:base map} legend be labelled; the first key is + labelled with the lower limit of the corresponding class interval, the + last key is labelled with the upper limit of the corresponding class + interval.{p_end} + +{phang} +{opt legjunction(string)} specifies the string to be used as separator + when option {cmd:legstyle(2)} is specified. The default is + {cmd:legjunction(" - ")}. + +{phang} +{opt legcount} requests that, when a {help spmap##choromap:choropleth map} + is drawn, the number of {help spmap##desc:base map} polygons belonging + to each class of variable {it:attribute} be displayed in the legend. + + +{marker polygon2}{title:Option polygon() suboptions} + +{dlgtab:Main} + +{phang} +{cmdab:data(}{help spmap##sd_polygon:{it:polygon}}{cmd:)} requests that one + or more supplementary polygons defined in Stata dataset {it:polygon} + be superimposed onto the {help spmap##desc:base map}. + +{phang} +{cmdab:select(}{help drop:{it:command}}{cmd:)} requests that a given subset + of records of dataset {it:polygon} be selected using Stata commands + {help drop:keep} or {help drop}. + +{phang} +{cmdab:by(}{help varname:{it:byvar_pl}}{cmd:)} indicates that the + supplementary polygons defined in dataset {it:polygon} belong + to {it:kpl} different groups specified by variable {it:byvar_pl}. + +{dlgtab:Format} + +{phang} +{cmdab:fcolor(}{help spmap##color:{it:colorlist}}{cmd:)} specifies the list + of fill colors of the supplementary polygons. When suboption + {opt by(byvar_pl)} is not specified, the list should include only one + element. On the other hand, when suboption {opt by(byvar_pl)} is + specified, the list should be either composed of {it:kpl} elements, + or represented by the name of a predefined + {help spmap##colorscheme:color scheme}. The default fill color is + {cmd:none}, the default specification is {cmd:fcolor(none{space 1}...)}. + +{phang} +{cmdab:ocolor(}{help spmap##color:{it:colorlist}}{cmd:)} specifies the list + of outline colors of the supplementary polygons. When suboption + {opt by(byvar_pl)} is not specified, the list should include only one + element. On the other hand, when suboption {opt by(byvar_pl)} is + specified, the list should be either composed of {it:kpl} elements, + or represented by the name of a predefined + {help spmap##colorscheme:color scheme}. The default outline color is + {cmd:black}, the default specification is {cmd:ocolor(black{space 1}...)}. + +{phang} +{cmdab:osize(}{it:{help linewidthstyle}_list}{cmd:)} specifies the + {help stylelists:list} of outline thicknesses of the supplementary + polygons. When suboption {opt by(byvar_pl)} is not specified, the + list should include only one element. On the other hand, when + suboption {opt by(byvar_pl)} is specified, the list should be + composed of {it:kpl} elements. The default outline thickness is + {cmd:thin}, the default specification is {cmd:osize(thin{space 1}...)}. + +{phang} +{cmdab:opattern(}{it:{help linepatternstyle}_list}{cmd:)} specifies the + {help stylelists:list} of outline patterns of the supplementary + polygons. When suboption {opt by(byvar_pl)} is not specified, the + list should include only one element. On the other hand, when + suboption {opt by(byvar_pl)} is specified, the list should be + composed of {it:kpl} elements. The default outline pattern is + {cmd:solid}, the default specification is + {cmd:opattern(solid{space 1}...)}. + +{dlgtab:Legend} + +{phang} +{cmdab:legenda(on}|{cmd:off)} specifies whether the supplementary-polygon + legend should be displayed or hidden. + +{phang2}{cmd:legenda(on)} requests that the supplementary-polygon legend + be displayed.{p_end} + +{phang2}{cmd:legenda(off)} is the default and requests that the + supplementary-polygon legend be hidden.{p_end} + +{phang} +{opt legtitle(string)} specifies the title of the supplementary-polygon + legend. When suboption {opt by(byvar_pl)} is specified, suboption + {cmd:legtitle(varlab)} requests that the label of variable {it:byvar_pl} + be used as the legend title. + +{phang} +{opt leglabel(string)} specifies the label to be attached to the single key of + the supplementary-polygon legend when suboption {opt by(byvar_pl)} is not + specified. This suboption is required when suboption {cmd:legenda(on)} is + specified and suboption {opt by(byvar_pl)} is not specified. + +{phang} +{opth legshow(numlist)} requests that, when suboption {opt by(byvar_pl)} is + specified, only the keys included in {it:numlist} be displayed in the + supplementary-polygon legend. + +{phang} +{opt legcount} requests that the number of supplementary polygons be displayed + in the legend. + + +{marker line2}{title:Option line() suboptions} + +{dlgtab:Main} + +{phang} +{cmdab:data(}{help spmap##sd_line:{it:line}}{cmd:)} requests that one + or more polylines defined in Stata dataset {it:line} be superimposed + onto the {help spmap##desc:base map}. + +{phang} +{cmdab:select(}{help drop:{it:command}}{cmd:)} requests that a given subset + of records of dataset {it:line} be selected using Stata commands + {help drop:keep} or {help drop}. + +{phang} +{cmdab:by(}{help varname:{it:byvar_ln}}{cmd:)} indicates that the + polylines defined in dataset {it:line} belong to {it:kln} different + groups specified by variable {it:byvar_ln}. + +{dlgtab:Format} + +{phang} +{cmdab:color(}{help spmap##color:{it:colorlist}}{cmd:)} specifies the list + of polyline colors. When suboption {opt by(byvar_ln)} is not specified, + the list should include only one element. On the other hand, when suboption + {opt by(byvar_ln)} is specified, the list should be either composed of + {it:kln} elements, or represented by the name of a predefined + {help spmap##colorscheme:color scheme}. The default color is {cmd:black}, + the default specification is {cmd:color(black{space 1}...)}. + +{phang} +{cmdab:size(}{it:{help linewidthstyle}_list}{cmd:)} specifies the + {help stylelists:list} of polyline thicknesses. When suboption + {opt by(byvar_ln)} is not specified, the list should include only + one element. On the other hand, when suboption {opt by(byvar_ln)} + is specified, the list should be composed of {it:kln} elements. The + default thickness is {cmd:thin}, the default specification is + {cmd:size(thin{space 1}...)}. + +{phang} +{cmdab:pattern(}{it:{help linepatternstyle}_list}{cmd:)} specifies the + {help stylelists:list} of polyline patterns. When suboption + {opt by(byvar_ln)} is not specified, the list should include only + one element. On the other hand, when suboption {opt by(byvar_ln)} + is specified, the list should be composed of {it:kln} elements. The + default pattern is {cmd:solid}, the default specification is + {cmd:pattern(solid{space 1}...)}. + +{dlgtab:Legend} + +{phang} +{cmdab:legenda(on}|{cmd:off)} specifies whether the polyline legend + should be displayed or hidden. + +{phang2}{cmd:legenda(on)} requests that the polyline legend be + displayed.{p_end} + +{phang2}{cmd:legenda(off)} is the default and requests that the + polyline legend be hidden.{p_end} + +{phang} +{opt legtitle(string)} specifies the title of the polyline legend. When + suboption {opt by(byvar_ln)} is specified, suboption {cmd:legtitle(varlab)} + requests that the label of variable {it:byvar_ln} be used as the legend + title. + +{phang} +{opt leglabel(string)} specifies the label to be attached to the single key of + the polyline legend when suboption {opt by(byvar_ln)} is not specified. This + suboption is required when suboption {cmd:legenda(on)} is specified and + suboption {opt by(byvar_ln)} is not specified. + +{phang} +{opth legshow(numlist)} requests that, when suboption {opt by(byvar_ln)} is + specified, only the keys included in {it:numlist} be displayed in the + polyline legend. + +{phang} +{opt legcount} requests that the number of polylines be displayed in the + legend. + + +{marker point2}{title:Option point() suboptions} + +{dlgtab:Main} + +{phang} +{cmdab:data(}{help spmap##sd_point:{it:point}}{cmd:)} requests that one + or more points defined in Stata dataset {it:point} be superimposed + onto the {help spmap##desc:base map}. + +{phang} +{cmdab:select(}{help drop:{it:command}}{cmd:)} requests that a given subset + of records of dataset {it:point} be selected using Stata commands + {help drop:keep} or {help drop}. + +{phang} +{cmdab:by(}{help varname:{it:byvar_pn}}{cmd:)} indicates that the + points defined in dataset {it:point} belong to {it:kpn} different + groups specified by variable {it:byvar_pn}. + +{phang} +{cmdab:xcoord(}{help varname:{it:xvar_pn}}{cmd:)} specifies the name of + the variable containing the {it:x}-coordinate of each point. + +{phang} +{cmdab:ycoord(}{help varname:{it:yvar_pn}}{cmd:)} specifies the name of + the variable containing the {it:y}-coordinate of each point. + +{dlgtab:Proportional size} + +{phang} +{cmd:proportional(}{help varname:{it:propvar_pn}}{cmd:)} requests that the + point markers be drawn with size proportional to the values taken on by + numeric variable {it:propvar_pn}. + +{phang} +{opt prange(min max)} requests that variable {it:propvar_pn} specified in + suboption {opt proportional(propvar_pn)} be normalized based on range + [{it:min}, {it:max}]. This suboption overrides the default normalization + based on range [0, max({it:propvar_pn})]. + +{phang} +{cmd:psize(relative}|{cmd:absolute)} specifies the reference system for + drawing the point markers. + +{phang2}{cmd:psize(relative)} is the default and requests that the point + markers be drawn using relative minimum and maximum reference values. This + is the best choice when there is no need to compare the map at hand with + other maps of the same kind.{p_end} + +{phang2}{cmd:psize(absolute)} requests that the point markers be drawn using + absolute minimum and maximum reference values. This is the best choice when + the map at hand is to be compared with other maps of the same kind.{p_end} + +{dlgtab:Deviation} + +{phang} +{cmd:deviation(}{help varname:{it:devvar_pn}}{cmd:)} requests that the + point markers be drawn as deviations from a reference value of numeric + variable {it:devvar_pn} specified in option {cmd:refval()}. When this + suboption is specified, in the first place the values of variable + {it:devvar_pn} are re-expressed as deviations from the chosen reference + value. Then, points associated with positive deviations are represented + by solid markers, whereas points associated with negative deviations are + represented by hollow markers of the same shape; in both cases, markers + are drawn with size proportional to the absolute value of the + deviation. This suboption is incompatible with suboption + {opt proportional(propvar_pn)}. + +{phang} +{cmd:refval(}{cmd:mean}|{cmd:median}|{it:#}{cmd:)} specifies the reference + value of variable {it:devvar_pn} for computing deviations. + +{phang2}{cmd:refval(mean)} is the default and requests that the arithmetic + mean of variable {it:devvar_pn} be taken as the reference value.{p_end} + +{phang2}{cmd:refval(median)} requests that the median of variable + {it:devvar_pn} be taken as the reference value.{p_end} + +{phang2}{cmd:refval(}{it:#}{cmd:)} requests that an arbitrary real value + {it:#} be taken as the reference value.{p_end} + +{phang} +{cmd:refweight(}{help varname:{it:weightvar_pn}}{cmd:)} requests that the + reference value of variable {it:devvar_pn} be computed weighting + observations by values of variable {it:weightvar_pn}. + +{phang} +{opt dmax(#)} requests that the point markers be drawn using value {it:#} + as the maximum absolute deviation of reference. + +{dlgtab:Format} + +{phang} +{cmd:size(}{it:{help markersizestyle}_list}{cmd:)} specifies the + {help stylelists:list} of point marker sizes. When suboption + {opt by(byvar_pn)} is not specified, suboption + {opt proportional(propvar_pn)} is specified, or suboption + {opt deviation(devvar_pn)} is specified, the list should include only + one element. On the other hand, when suboption {opt by(byvar_pn)} + is specified and neither suboptions {opt proportional(propvar_pn)} + and {opt deviation(devvar_pn)} are specified, the list should be + composed of {it:kpn} elements. The default size is {cmd:*1}, the + default specification is {cmd:size(*1{space 1}...)}. + +{phang} +{cmd:shape(}{it:{help symbolstyle}_list}{cmd:)} specifies the + {help stylelists:list} of point marker shapes. When suboption + {opt by(byvar_pn)} is not specified, the list should include only + one element. On the other hand, when suboption {opt by(byvar_pn)} + is specified, the list should be composed of {it:kpn} elements. The + default shape is {cmd:o}, the default specification is + {cmd:shape(o{space 1}...)}. When suboption {opt deviation(devvar_pn)} + is specified, this suboption accepts only solid + {help symbolstyle:{it:symbolstyles}} written in short + form: {cmd:O D T S o d t s}. + +{phang} +{cmd:fcolor(}{help spmap##color:{it:colorlist}}{cmd:)} specifies the list + of fill colors of the point markers. When suboption {opt by(byvar_pn)} + is not specified, the list should include only one element. On the other + hand, when suboption {opt by(byvar_pn)} is specified, the list should be + either composed of {it:kpn} elements, or represented by the name of a + predefined {help spmap##colorscheme:color scheme}. The default fill color + is {cmd:black}, the default specification is + {cmd:fcolor(black{space 1}...)}. + +{phang} +{cmd:ocolor(}{help spmap##color:{it:colorlist}}{cmd:)} specifies the list + of outline colors of the point markers. When suboption {opt by(byvar_pn)} + is not specified, the list should include only one element. On the other + hand, when suboption {opt by(byvar_pn)} is specified, the list should be + either composed of {it:kpn} elements, or represented by the name of a + predefined {help spmap##colorscheme:color scheme}. The default outline + color is {cmd:none}, the default specification is + {cmd:ocolor(none{space 1}...)}. + +{phang} +{cmd:osize(}{it:{help linewidthstyle}_list}{cmd:)} specifies the + {help stylelists:list} of outline thicknesses of the point markers. When + suboption {opt by(byvar_pn)} is not specified, the list should include + only one element. On the other hand, when suboption {opt by(byvar_pn)} + is specified, the list should be composed of {it:kpl} elements. The default + outline thickness is {cmd:thin}, the default specification is + {cmd:osize(thin{space 1}...)}. + +{dlgtab:Legend} + +{phang} +{cmdab:legenda(on}|{cmd:off)} specifies whether the point legend + should be displayed or hidden. + +{phang2}{cmd:legenda(on)} requests that the point legend be + displayed.{p_end} + +{phang2}{cmd:legenda(off)} is the default and requests that the + point legend be hidden.{p_end} + +{phang} +{opt legtitle(string)} specifies the title of the point legend. When + suboption {opt by(byvar_pn)} is specified, suboption {cmd:legtitle(varlab)} + requests that the label of variable {it:byvar_pn} be used as the legend + title. + +{phang} +{opt leglabel(string)} specifies the label to be attached to the single key of + the point legend when suboption {opt by(byvar_pn)} is not specified. This + suboption is required when suboption {cmd:legenda(on)} is specified and + suboption {opt by(byvar_pn)} is not specified. + +{phang} +{opth legshow(numlist)} requests that, when suboption {opt by(byvar_pn)} is + specified, only the keys included in {it:numlist} be displayed in the + point legend. + +{phang} +{opt legcount} requests that the number of points be displayed in the legend. + + +{marker diagram2}{title:Option diagram() suboptions} + +{dlgtab:Main} + +{phang} +{cmd:data(}{help spmap##sd_diagram:{it:diagram}}{cmd:)} requests that one + or more diagrams defined in Stata dataset {it:diagram} be superimposed + onto the {help spmap##desc:base map} at given reference points. + +{phang} +{cmd:select(}{help drop:{it:command}}{cmd:)} requests that a given subset + of records of dataset {it:diagram} be selected using Stata commands + {help drop:keep} or {help drop}. + +{phang} +{cmd:by(}{help varname:{it:byvar_dg}}{cmd:)} indicates that the + diagrams defined in dataset {it:diagram} belong to {it:kdg} different + groups specified by variable {it:byvar_dg}. This option is active only + when just one variable is specified in suboption + {opt variables(diagvar_dg)}. + +{phang} +{cmd:xcoord(}{help varname:{it:xvar_dg}}{cmd:)} specifies the name of + the variable containing the {it:x}-coordinate of each diagram reference + point. + +{phang} +{cmd:ycoord(}{help varname:{it:yvar_dg}}{cmd:)} specifies the name of + the variable containing the {it:y}-coordinate of each diagram reference + point. + +{phang} +{cmd:variables(}{help varname:{it:diagvar_dg}}{cmd:)} specifies the list of + variables to be represented by the diagrams. + +{phang} +{cmd:type(frect}|{cmd:pie)} specifies the type of diagram to be used. + +{phang2}{cmd:type(frect)} is the default when only one variable is specified + in suboption {opt variables(diagvar_dg)} and requests that framed-rectangle + charts (Cleveland and McGill 1984; Cleveland 1994) be used.{p_end} + +{phang2}{cmd:type(pie)} is the default (and the only possibility) when two + or more variables are specified in suboption {opt variables(diagvar_dg)} + and requests that pie charts be used. When option {cmd:type(pie)} is + specified, the variables specified in suboption {opt variables(diagvar_dg)} + are rescaled so that they sum to 1 within each observation.{p_end} + +{dlgtab:Proportional size} + +{phang} +{cmdab:proportional(}{help varname:{it:propvar_dg}}{cmd:)} requests that the + diagrams be drawn with size proportional to the values taken on by + numeric variable {it:propvar_dg}. + +{phang} +{opt prange(min max)} requests that variable {it:propvar_dg} specified in + suboption {opt proportional(propvar_dg)} be normalized based on range + [{it:min}, {it:max}]. This suboption overrides the default normalization + based on range [0, max({it:propvar_dg})]. + +{dlgtab:Framed-rectangle chart} + +{phang} +{opt range(min max)} requests that variable {it:diagvar_dg} specified in + suboption {opt variables(diagvar_dg)} be normalized based on range + [{it:min}, {it:max}]. This suboption overrides the default normalization + based on range [0, max({it:diagvar_dg})]. + +{phang} +{cmd:refval(}{cmd:mean}|{cmd:median}|{it:#}{cmd:)} specifies the reference + value of variable {it:diagvar_dg} for drawing the reference line. + +{phang2}{cmd:refval(mean)} is the default and requests that the arithmetic + mean of variable {it:diagvar_dg} be taken as the reference value.{p_end} + +{phang2}{cmd:refval(median)} requests that the median of variable + {it:diagvar_dg} be taken as the reference value.{p_end} + +{phang2}{cmd:refval(}{it:#}{cmd:)} requests that an arbitrary real value + {it:#} be taken as the reference value.{p_end} + +{phang} +{cmdab:refweight(}{help varname:{it:weightvar_dg}}{cmd:)} requests that the + reference value of variable {it:diagvar_dg} be computed weighting + observations by values of variable {it:weightvar_dg}. + +{phang} +{opth refcolor(colorstyle)} specifies the color of the reference line. The + default is {cmd:refcolor(black)}. + +{phang} +{opth refsize(linewidthstyle)} specifies the thickness of the reference + line. The default is {cmd:refsize(medium)}. + +{dlgtab:Format} + +{phang} +{opt size(#)} specifies a multiplier that affects the size of the + diagrams. For example, {cmd:size(1.5)} requests that the default size + of all the diagrams be increased by 50%. The default is {cmd:size(1)}. + +{phang} +{cmdab:fcolor(}{help spmap##color:{it:colorlist}}{cmd:)} specifies the list + of fill colors of the diagrams. When just one variable is specified in + suboption {opt variables(diagvar_dg)} and suboption {opt by(byvar_dg)} is + not specified, the list should include only one element. When just one + variable is specified in suboption {opt variables(diagvar_dg)} and + suboption {opt by(byvar_dg)} is specified, the list should be either + composed of {it:kdg} elements, or represented by the name of a predefined + {help spmap##colorscheme:color scheme}. Finally, when {it:J}>1 variables + are specified in suboption {opt variables(diagvar_dg)}, the list should + be either composed of {it:J} elements, or represented by the name of a + predefined {help spmap##colorscheme:color scheme}. The default fill color + is {cmd:black}, the default specification when {it:J}=1 is + {cmd:fcolor(black{space 1}...)}, and the default specification when + {it:J}>1 is {cmd:fcolor(red blue orange green lime navy sienna ltblue} + {cmd:cranberry emerald eggshell magenta olive brown yellow dkgreen)}. + +{phang} +{cmdab:ocolor(}{help spmap##color:{it:colorlist}}{cmd:)} specifies the list + of outline colors of the diagrams. When just one variable is specified in + suboption {opt variables(diagvar_dg)} and suboption {opt by(byvar_dg)} is + not specified, the list should include only one element. When just one + variable is specified in suboption {opt variables(diagvar_dg)} and + suboption {opt by(byvar_dg)} is specified, the list should be either + composed of {it:kdg} elements, or represented by the name of a predefined + {help spmap##colorscheme:color scheme}. Finally, when {it:J}>1 variables + are specified in suboption {opt variables(diagvar_dg)}, the list should + be either composed of {it:J} elements, or represented by the name of a + predefined {help spmap##colorscheme:color scheme}. The default fill color + is {cmd:black}, the default specification is {cmd:ocolor(black{space 1}...)}. + +{phang} +{cmdab:osize(}{it:{help linewidthstyle}_list}{cmd:)} specifies the list of + outline thicknesses of the diagrams. When just one variable is specified + in suboption {opt variables(diagvar_dg)} and suboption {opt by(byvar_dg)} + is not specified, the list should include only one element. When just one + variable is specified in suboption {opt variables(diagvar_dg)} and + suboption {opt by(byvar_dg)} is specified, the list should be composed + of {it:kdg} elements. Finally, when {it:J}>1 variables are specified in + suboption {opt variables(diagvar_dg)}, the list should be composed of + {it:J} elements. The default outline thickness is {cmd:thin}, the default + specification is {cmd:osize(thin{space 1}...)}. + +{dlgtab:Legend} + +{phang} +{cmdab:legenda(on}|{cmd:off)} specifies whether the diagram legend + should be displayed or hidden. + +{phang2}{cmd:legenda(on)} requests that the diagram legend be + displayed.{p_end} + +{phang2}{cmd:legenda(off)} is the default and requests that the + point diagram be hidden.{p_end} + +{phang} +{opt legtitle(string)} specifies the title of the diagram legend. When just + one variable is specified in suboption {opt variables(diagvar_dg)}, + suboption {cmd:legtitle(varlab)} requests that the label of variable + {it:diagvar_dg} be used as the legend title. + +{phang} +{opth legshow(numlist)} requests that only the keys included in {it:numlist} + be displayed in the diagram legend. + +{phang} +{opt legcount} requests that the number of diagrams be displayed in the legend. + + +{marker arrow2}{title:Option arrow() suboptions} + +{dlgtab:Main} + +{phang} +{cmdab:data(}{help spmap##sd_arrow:{it:arrow}}{cmd:)} requests that one + or more arrows defined in Stata dataset {it:arrow} be superimposed + onto the {help spmap##desc:base map}. + +{phang} +{cmdab:select(}{help drop:{it:command}}{cmd:)} requests that a given subset + of records of dataset {it:arrow} be selected using Stata commands + {help drop:keep} or {help drop}. + +{phang} +{cmdab:by(}{help varname:{it:byvar_ar}}{cmd:)} indicates that the + arrows defined in dataset {it:arrow} belong to {it:kar} different + groups specified by variable {it:byvar_ar}. + +{dlgtab:Format} + +{phang} +{opt direction(directionstyle_list)} specifies the {help stylelists:list} of + arrow directions, where {it:directionstyle} is one of the following: + {cmd:1} (monodirectional arrow), {cmd:2} (bidirectional arrow). When + suboption {opt by(byvar_ar)} is not specified, the list should include + only one element. On the other hand, when suboption {opt by(byvar_ar)} is + specified, the list should be composed of {it:kar} elements. The default + direction is {cmd:1}, the default specification is + {cmd:direction(1{space 1}...)}. + +{phang} +{cmdab:hsize(}{it:{help markersizestyle}_list}{cmd:)} specifies the + {help stylelists:list} of arrowhead sizes. When suboption + {opt by(byvar_ar)} is not specified, the list should include only + one element. On the other hand, when suboption {opt by(byvar_ar)} + is specified, the list should be composed of {it:kar} elements. The + default size is {cmd:1.5}, the default specification is + {cmd:hsize(1.5{space 1}...)}. + +{phang} +{cmdab:hangle(}{it:{help anglestyle}_list}{cmd:)} specifies the + {help stylelists:list} of arrowhead angles. When suboption + {opt by(byvar_ar)} is not specified, the list should include only + one element. On the other hand, when suboption {opt by(byvar_ar)} + is specified, the list should be composed of {it:kar} elements. The + default angle is {cmd:28.64}, the default specification is + {cmd:hangle(28.64{space 1}...)}. + +{phang} +{cmdab:hbarbsize(}{it:{help markersizestyle}_list}{cmd:)} specifies the + {help stylelists:list} of sizes of the filled portion of arrowheads. When + suboption {opt by(byvar_ar)} is not specified, the list should include only + one element. On the other hand, when suboption {opt by(byvar_ar)} is + specified, the list should be composed of {it:kar} elements. The default + size is {cmd:1.5}, the default specification is + {cmd:hbarbsize(1.5{space 1}...)}. + +{phang} +{cmdab:hfcolor(}{help spmap##color:{it:colorlist}}{cmd:)} specifies the list + of arrowhead fill colors. When suboption {opt by(byvar_ar)} is not + specified, the list should include only one element. On the other hand, + when suboption {opt by(byvar_ar)} is specified, the list should be either + composed of {it:kar} elements, or represented by the name of a predefined + {help spmap##colorscheme:color scheme}. The default fill color is + {cmd:black}, the default specification is {cmd:hfcolor(black{space 1}...)}. + +{phang} +{cmdab:hocolor(}{help spmap##color:{it:colorlist}}{cmd:)} specifies the list + of arrowhead outline colors. When suboption {opt by(byvar_ar)} is not + specified, the list should include only one element. On the other hand, + when suboption {opt by(byvar_ar)} is specified, the list should be either + composed of {it:kar} elements, or represented by the name of a predefined + {help spmap##colorscheme:color scheme}. The default outline color is + {cmd:black}, the default specification is {cmd:hocolor(black{space 1}...)}. + +{phang} +{cmdab:hosize(}{it:{help linewidthstyle}_list}{cmd:)} specifies the + {help stylelists:list} of arrowhead outline thicknesses. When suboption + {opt by(byvar_ar)} is not specified, the list should include only + one element. On the other hand, when suboption {opt by(byvar_ar)} + is specified, the list should be composed of {it:kar} elements. The + default outline thickness is {cmd:thin}, the default specification is + {cmd:hosize(thin{space 1}...)}. + +{phang} +{cmdab:lcolor(}{help spmap##color:{it:colorlist}}{cmd:)} specifies the list + of arrow shaft line colors. When suboption {opt by(byvar_ar)} is not + specified, the list should include only one element. On the other hand, + when suboption {opt by(byvar_ar)} is specified, the list should be either + composed of {it:kar} elements, or represented by the name of a predefined + {help spmap##colorscheme:color scheme}. The default color is {cmd:black}, + the default specification is {cmd:lcolor(black{space 1}...)}. + +{phang} +{cmdab:lsize(}{it:{help linewidthstyle}_list}{cmd:)} specifies the + {help stylelists:list} of arrow shaft line thicknesses. When suboption + {opt by(byvar_ar)} is not specified, the list should include only + one element. On the other hand, when suboption {opt by(byvar_ar)} + is specified, the list should be composed of {it:kar} elements. The + default thickness is {cmd:thin}, the default specification is + {cmd:lsize(thin{space 1}...)}. + +{phang} +{cmdab:lpattern(}{it:{help linepatternstyle}_list}{cmd:)} specifies the + {help stylelists:list} of arrow shaft line patterns. When suboption + {opt by(byvar_ar)} is not specified, the list should include only + one element. On the other hand, when suboption {opt by(byvar_ar)} + is specified, the list should be composed of {it:kar} elements. The + default pattern is {cmd:solid}, the default specification is + {cmd:lpattern(solid{space 1}...)}. + +{dlgtab:Legend} + +{phang} +{cmdab:legenda(on}|{cmd:off)} specifies whether the arrow legend + should be displayed or hidden. + +{phang2}{cmd:legenda(on)} requests that the arrow legend be + displayed.{p_end} + +{phang2}{cmd:legenda(off)} is the default and requests that the + arrow legend be hidden.{p_end} + +{phang} +{opt legtitle(string)} specifies the title of the arrow legend. When + suboption {opt by(byvar_ar)} is specified, suboption {cmd:legtitle(varlab)} + requests that the label of variable {it:byvar_ar} be used as the legend + title. + +{phang} +{opt leglabel(string)} specifies the label to be attached to the single key of + the arrow legend when suboption {opt by(byvar_ar)} is not specified. This + suboption is required when suboption {cmd:legenda(on)} is specified and + suboption {opt by(byvar_ar)} is not specified. + +{phang} +{opth legshow(numlist)} requests that, when suboption {opt by(byvar_ar)} is + specified, only the keys included in {it:numlist} be displayed in the + arrow legend. + +{phang} +{opt legcount} requests that the number of arrows be displayed in the + legend. + + +{marker label2}{title:Option label() suboptions} + +{dlgtab:Main} + +{phang} +{cmdab:data(}{help spmap##sd_label:{it:label}}{cmd:)} requests that one + or more labels defined in Stata dataset {it:label} be superimposed + onto the {help spmap##desc:base map} at given reference points. + +{phang} +{cmdab:select(}{help drop:{it:command}}{cmd:)} requests that a given subset + of records of dataset {it:label} be selected using Stata commands + {help drop:keep} or {help drop}. + +{phang} +{cmdab:by(}{help varname:{it:byvar_lb}}{cmd:)} indicates that the + labels defined in dataset {it:label} belong to {it:klb} different + groups specified by variable {it:byvar_lb}. + +{phang} +{cmdab:xcoord(}{help varname:{it:xvar_lb}}{cmd:)} specifies the name of + the variable containing the {it:x}-coordinate of each label reference + point. + +{phang} +{cmdab:ycoord(}{help varname:{it:yvar_lb}}{cmd:)} specifies the name of + the variable containing the {it:y}-coordinate of each label reference + point. + +{phang} +{cmdab:label(}{help varname:{it:labvar_lb}}{cmd:)} specifies the name of + the variable containing the labels. + +{dlgtab:Format} + +{phang} +{opt length(lengthstyle_list)} specifies the {help stylelists:list} of + label lengths, where {it:lengthstyle} is any integer greater than 0 + indicating the maximum number of characters of the labels. When + suboption {opt by(byvar_lb)} is not specified, the list should include + only one element. On the other hand, when suboption {opt by(byvar_lb)} is + specified, the list should be composed of {it:klb} elements. The default + label lenght is {cmd:12}, the default specification is {cmd:length(12 ...)}. + +{phang} +{cmdab:size(}{it:{help textsizestyle}_list}{cmd:)} specifies the + {help stylelists:list} of label sizes. When suboption {opt by(byvar_lb)} + is not specified, the list should include only one element. On the other + hand, when suboption {opt by(byvar_lb)} is specified, the list should be + composed of {it:klb} elements. The default label size is {cmd:*1}, the + default specification is {cmd:size(*1 ...)}. + +{phang} +{cmdab:color(}{help spmap##color:{it:colorlist}}{cmd:)} specifies the list + of label colors. When suboption {opt by(byvar_lb)} is not specified, the + list should include only one element. On the other hand, when suboption + {opt by(byvar_lb)} is specified, the list should be either composed of + {it:klb} elements, or represented by the name of a predefined + {help spmap##colorscheme:color scheme}. The default label color is + {cmd:black}, the default specification is {cmd:color(black ...)}. + +{phang} +{cmdab:position(}{it:{help clockpos}_list}{cmd:)} specifies the + {help stylelists:list} of label positions relative to their reference + point. When suboption {opt by(byvar_lb)} is not specified, the list + should include only one element. On the other hand, when suboption + {opt by(byvar_lb)} is specified, the list should be composed of {it:klb} + elements. The default label position is {cmd:0}, the default specification + is {cmd:position(0 ...)}. + +{phang} +{cmdab:gap(}{it:{help relativesize}_list}{cmd:)} specifies the + {help stylelists:list} of gaps between labels and their reference + point. When suboption {opt by(byvar_lb)} is not specified, the list + should include only one element. On the other hand, when suboption + {opt by(byvar_lb)} is specified, the list should be composed of {it:klb} + elements. The default label gap is {cmd:*1}, the default specification + is {cmd:gap(*1 ...)}. + +{phang} +{cmdab:angle(}{it:{help anglestyle}_list}{cmd:)} specifies the + {help stylelists:list} of label angles. When suboption {opt by(byvar_lb)} + is not specified, the list should include only one element. On the other + hand, when suboption {opt by(byvar_lb)} is specified, the list should be + composed of {it:klb} elements. The default label angle is {cmd:horizontal}, + the default specification is {cmd:angle(horizontal ...)}. + + +{marker scalebar2}{title:Option scalebar() suboptions} + +{dlgtab:Main} + +{phang} +{opt units(#)} specifies the length of the scale bar expressed in + arbitrary units. + +{phang} +{opt scale(#)} specifies the ratio of scale bar units to map units. For + example, suppose map coordinates are expressed in meters: if the scale + bar length is to be expressed in meters too, then the ratio of scale + bar units to map units will be 1; if, on the other hand, the scale + bar length is to be expressed in kilometers, then the ratio of scale + bar units to map units will be 1/1000. The default is {cmd:scale(1)}. + +{phang} +{opt xpos(#)} specifies the distance of the scale bar from the center + of the {help region_options:plot region} on the horizontal axis, + expressed as percentage of half the total width of the + {help region_options:plot region}. Positive values request that the + distance be computed from the center to the right, whereas negative + values request that the distance be computed from the center to the + left. The default is {cmd:xpos(0)}. + +{phang} +{opt ypos(#)} specifies the distance of the scale bar from the center + of the {help region_options:plot region} on the vertical axis, + expressed as percentage of half the total height of the + {help region_options:plot region}. Positive values request that the + distance be computed from the center to the top, whereas negative + values request that the distance be computed from the center to the + bottom. The default is {cmd:ypos(-110)}. + +{dlgtab:Format} + +{phang} +{opt size(#)} specifies a multiplier that affects the height of the + scale bar. For example, {cmd:size(1.5)} requests that the default + height of the scale bar be increased by 50%. The default is + {cmd:size(1)}. + +{phang} +{opth fcolor(colorstyle)} specifies the fill color of the scale bar. The + default is {cmd:fcolor(black)}. + +{phang} +{opth ocolor(colorstyle)} specifies the outline color of the scale bar. The + default is {cmd:ocolor(black)}. + +{phang} +{opth osize(linewidthstyle)} specifies the outline thickness of the scale + bar. The default is {cmd:osize(vthin)}. + +{phang} +{opt label(string)} specifies the descriptive label of the scale bar. The + default is {cmd:label(Units)}. + +{phang} +{opth tcolor(colorstyle)} specifies the color of the scale bar text. The + default is {cmd:tcolor(black)}. + +{phang} +{opth tsize(textsizestyle)} specifies the size of the scale bar text. The + default is {cmd:tsize(*1)}. + + +{marker graph2}{title:Graph options} + +{dlgtab:Main} + +{phang} +{opt polyfirst} requests that the supplementary polygons specified in option + {cmd:polygon()} be drawn before the base map. By default, the base map + is drawn before any other spatial object. + +{phang} +{opt gsize(#)} specifies the length (in inches) of the shortest side of the + graph {it: available area} (the lenght of the longest side is set + internally by {cmd:spmap} to minimize the amount of blank space around + the map). The default ranges from 1 to 4, depending on the aspect ratio + of the map. Alternatively, the height and width of the graph + {it: available area} can be set using the standard + {bf:{help region_options:xsize()}} and {bf:{help region_options:ysize()}} + options. + +{phang} +{opt freestyle} requests that, when drawing the graph, all the formatting + presets and restrictions built in {cmd:spmap} be ignored. By default, + {cmd:spmap} presets the values of some graph options and restricts the + use of some others, so as to produce a "nice" graph automatically. By + specifying option {cmd:freestyle}, the user loses this feature but gains + full control over most of the graph formatting options. + +{phang} +{it:{help twoway_options}} include all the options documented in + {bind:{bf:[G] {it:twoway_options}}}, except for + {it:aspect_option}, {it:scheme_option}, {it:by_option}, and + {it:advanced_options}. These include {it:{help added_line_options}}, + {it:{help added_text_options}}, {it:{help axis_options}}, + {it:{help title_options}}, {it:{help legend_option}}, + and {it:{help region_options}}, + as well as options {bf:{help nodraw_option:nodraw}}, + {bf:{help name_option:name()}}, and {bf:{help saving_option:saving()}}. When + option {cmd:freestyle} is specified, it is possible to control also + {it:{help aspect_option}} and {it:{help scheme_option}}. + + +{title:Examples 1: Choropleth maps} + +{p 4 10 2} +NOTE: All the examples illustrated in the present and in the following sections + can be run by clicking on the blue hyperlinks only if Stata is called + from the directory where the {cmd:spmap} ancillary datasets are located. + +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) +{txt} ({stata "spmap_examples chomap01":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) +{txt} ({stata "spmap_examples chomap02":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(2) legend(region(lcolor(black))) +{txt} ({stata "spmap_examples chomap03":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1m using "Italy-RegionsCoordinates.dta", id(id) /// + ndfcolor(red) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(2) legend(region(lcolor(black))) +{txt} ({stata "spmap_examples chomap04":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clmethod(eqint) clnumber(5) eirange(20 70) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(2) legend(region(lcolor(black))) +{txt} ({stata "spmap_examples chomap05":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Reds2) ocolor(none ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) +{txt} ({stata "spmap_examples chomap06":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Reds2) ocolor(none ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) legend(ring(1) position(3)) +{txt} ({stata "spmap_examples chomap07":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Reds2) ocolor(none ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) legend(ring(1) position(3)) /// + plotregion(margin(vlarge)) +{txt} ({stata "spmap_examples chomap08":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Reds2) ocolor(none ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) legend(ring(1) position(3)) /// + plotregion(icolor(stone)) graphregion(icolor(stone)) +{txt} ({stata "spmap_examples chomap09":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Greens2) ocolor(white ..) osize(medthin ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) legend(ring(1) position(3)) /// + plotregion(icolor(stone)) graphregion(icolor(stone)) +{txt} ({stata "spmap_examples chomap10":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Greens2) ocolor(white ..) osize(thin ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) legend(ring(1) position(3)) /// + plotregion(icolor(stone)) graphregion(icolor(stone)) /// + polygon(data("Italy-Highlights.dta") ocolor(white) /// + osize(medthick)) +{txt} ({stata "spmap_examples chomap11":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Greens2) ocolor(white ..) osize(medthin ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) legend(ring(1) position(3)) /// + plotregion(icolor(stone)) graphregion(icolor(stone)) /// + scalebar(units(500) scale(1/1000) xpos(-100) label(Kilometers)) +{txt} ({stata "spmap_examples chomap12":click to run}) + + +{title:Examples 2: Proportional symbol maps} +{cmd} + . use "Italy-OutlineData.dta", clear + . spmap using "Italy-OutlineCoordinates.dta", id(id) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) proportional(relig1) fcolor(red) size(*1.5)) +{txt} ({stata "spmap_examples prsmap01":click to run}) +{cmd} + . use "Italy-OutlineData.dta", clear + . spmap using "Italy-OutlineCoordinates.dta", id(id) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) proportional(relig1) fcolor(red) size(*1.5) /// + shape(s)) +{txt} ({stata "spmap_examples prsmap02":click to run}) +{cmd} + . use "Italy-OutlineData.dta", clear + . spmap using "Italy-OutlineCoordinates.dta", id(id) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) proportional(relig1) fcolor(red) /// + ocolor(white) size(*3)) /// + label(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) label(relig1) color(white) size(*0.7)) +{txt} ({stata "spmap_examples prsmap03":click to run}) +{cmd} + . use "Italy-OutlineData.dta", clear + . spmap using "Italy-OutlineCoordinates.dta", id(id) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) deviation(relig1) fcolor(red) dmax(30) /// + legenda(on) leglabel(Deviation from the mean)) +{txt} ({stata "spmap_examples prsmap04":click to run}) +{cmd} + . use "Italy-OutlineData.dta", clear + . spmap using "Italy-OutlineCoordinates.dta", id(id) fcolor(white) /// + title("Catholics without reservations", size(*0.9) box bexpand /// + span margin(medsmall) fcolor(sand)) subtitle(" ") /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) proportional(relig1) prange(0 70) /// + psize(absolute) fcolor(red) ocolor(white) size(*0.6)) /// + plotregion(margin(medium) color(stone)) /// + graphregion(fcolor(stone) lcolor(black)) /// + name(g1, replace) nodraw + . spmap using "Italy-OutlineCoordinates.dta", id(id) fcolor(white) /// + title("Catholics with reservations", size(*0.9) box bexpand /// + span margin(medsmall) fcolor(sand)) subtitle(" ") /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) proportional(relig2) prange(0 70) /// + psize(absolute) fcolor(green) ocolor(white) size(*0.6)) /// + plotregion(margin(medium) color(stone)) /// + graphregion(fcolor(stone) lcolor(black)) /// + name(g2, replace) nodraw + . spmap using "Italy-OutlineCoordinates.dta", id(id) fcolor(white) /// + title("Other", size(*0.9) box bexpand /// + span margin(medsmall) fcolor(sand)) subtitle(" ") /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) proportional(relig3) prange(0 70) /// + psize(absolute) fcolor(blue) ocolor(white) size(*0.6)) /// + plotregion(margin(medium) color(stone)) /// + graphregion(fcolor(stone) lcolor(black)) /// + name(g3, replace) nodraw + . graph combine g1 g2 g3, rows(1) title("Religious orientation") /// + subtitle("Italy, 1994-98" " ") xsize(5) ysize(2.6) /// + plotregion(margin(medsmall) style(none)) /// + graphregion(margin(zero) style(none)) /// + scheme(s1mono) +{txt} ({stata "spmap_examples prsmap05":click to run}) + + +{title:Examples 3: Other maps} +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap using "Italy-RegionsCoordinates.dta", id(id) fcolor(stone) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + diagram(variable(relig1) range(0 100) refweight(pop98) /// + xcoord(xcoord) ycoord(ycoord) fcolor(red)) +{txt} ({stata "spmap_examples othmap01":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap using "Italy-RegionsCoordinates.dta", id(id) fcolor(stone) /// + diagram(variable(relig1 relig2 relig3) proportional(fortell) /// + xcoord(xcoord) ycoord(ycoord) legenda(on)) /// + legend(title("Religious orientation", size(*0.5) bexpand /// + justification(left))) /// + note(" " /// + "NOTE: Chart size proportional to number of fortune tellers per million population", /// + size(*0.75)) +{txt} ({stata "spmap_examples othmap02":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clmethod(stdev) clnumber(5) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) area(pop98) /// + note(" " /// + "NOTE: Region size proportional to population", size(*0.75)) +{txt} ({stata "spmap_examples othmap03":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clmethod(stdev) clnumber(5) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) area(pop98) /// + map("Italy-OutlineCoordinates.dta") mfcolor(stone) /// + note(" " /// + "NOTE: Region size proportional to population", size(*0.75)) +{txt} ({stata "spmap_examples othmap04":click to run}) +{cmd} + . use "Italy-OutlineData.dta", clear + . spmap using "Italy-OutlineCoordinates.dta", id(id) fc(bluishgray) /// + ocolor(none) /// + title("Provincial capitals" " ", size(*0.9) color(white)) /// + point(data("Italy-Capitals.dta") xcoord(xcoord) /// + ycoord(ycoord) fcolor(emerald)) /// + plotregion(margin(medium) icolor(dknavy) color(dknavy)) /// + graphregion(icolor(dknavy) color(dknavy)) +{txt} ({stata "spmap_examples othmap05":click to run}) +{cmd} + . use "Italy-OutlineData.dta", clear + . spmap using "Italy-OutlineCoordinates.dta", id(id) fc(bluishgray) /// + ocolor(none) /// + title("Provincial capitals" " ", size(*0.9) color(white)) /// + point(data("Italy-Capitals.dta") xcoord(xcoord) /// + ycoord(ycoord) by(size) fcolor(orange red maroon) shape(s ..) /// + legenda(on)) /// + legend(title("Population 1998", size(*0.5) bexpand /// + justification(left)) region(lcolor(black) fcolor(white)) /// + position(2)) /// + plotregion(margin(medium) icolor(dknavy) color(dknavy)) /// + graphregion(icolor(dknavy) color(dknavy)) +{txt} ({stata "spmap_examples othmap06":click to run}) +{cmd} + . use "Italy-OutlineData.dta", clear + . spmap using "Italy-OutlineCoordinates.dta", id(id) fc(sand) /// + title("Main lakes and rivers" " ", size(*0.9)) /// + polygon(data("Italy-Lakes.dta") fcolor(blue) ocolor(blue)) /// + line(data("Italy-Rivers.dta") color(blue) ) +{txt} ({stata "spmap_examples othmap07":click to run}) +{cmd} + . use "Italy-RegionsData.dta", clear + . spmap relig1 using "Italy-RegionsCoordinates.dta" if zone==1, /// + id(id) fcolor(Blues2) ocolor(white ..) osize(medthin ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Northern Italy, 1994-98" " ", size(*0.8)) /// + polygon(data("Italy-OutlineCoordinates.dta") fcolor(gs12) /// + ocolor(white) osize(medthin)) polyfirst +{txt} ({stata "spmap_examples othmap08":click to run}) +{cmd} + . use "Italy-OutlineData.dta", clear + . spmap using "Italy-OutlineCoordinates.dta", id(id) fc(sand) /// + title("Main lakes and rivers" " ", size(*0.9)) /// + polygon(data("Italy-Lakes.dta") fcolor(blue) ocolor(blue)) /// + line(data("Italy-Rivers.dta") color(blue) ) /// + freestyle aspect(1.4) xlab(400000 900000 1400000, grid) +{txt} ({stata "spmap_examples othmap09":click to run}) + + +{title:Acknowledgments} + +{p 4 4 2} I wish to thank Nick Cox, Ian Evans, and Vince Wiggins for helping + set up {cmd:tmap} (Pisati 2004), the predecessor of {cmd:spmap}. I also + thank Kevin Crow, Bill Gould, Friedrich Huebler, and Scott Merryman for + promoting {cmd:tmap} by making available to the Stata community several + helpful resources related to the program. The development of {cmd:spmap} + benefitted from suggestions by Jo{c 227}o Pedro Azevedo, Kit Baum, Daniele + Checchi, Kevin Crow, David Drukker, Friedrich Huebler, Laszlo Kardos, Ulrich + Kohler, Mattia Landoni, Scott Merryman, Derek Wagner, the participants in + the 1st Italian Stata Users Group Meeting, and the participants in the 3rd + German Stata Users Group Meeting: many thanks to all of them. + + +{title:Author} + +{p 4} Maurizio Pisati {p_end} +{p 4} Department of Sociology and Social Research {p_end} +{p 4} University of Milano Bicocca - Italy {p_end} +{p 4} {browse "mailto:maurizio.pisati@unimib.it":maurizio.pisati@unimib.it} + + +{title:References} + +{p 4 8 2}Armstrong, M.P., Xiao, N. and D.A. Bennett. 2003. Using genetic +algorithms to create multicriteria class intervals for choropleth +maps. {it:Annals of the Association of American Geographers} 93: 595{c -}623. + +{p 4 8 2}Brewer, C.A. 1999. Color use guidelines for data +representation. {it:Proceedings of the Section on Statistical } +{it: Graphics, American Statistical Association}. Alexandria VA, +55{c -}60. + +{p 4 8 2}Brewer, C.A., Hatchard, G.W. and M.A. Harrower. 2003. ColorBrewer +in print: A catalog of color schemes for maps. {it:Cartography and Geographic} +{it:Information Science} 52: 5{c -}32. + +{p 4 8 2}Cleveland, W.S. 1994. {it:The Elements of Graphing Data}. Summit: Hobart +Press. + +{p 4 8 2}Cleveland, W.S. and R. McGill. 1984. Graphical perception: Theory, +experimentation, and application to the development of graphical +methods. {it:Journal of the American Statistical Association} 79: 531{c -}554. + +{p 4 8 2}Evans, I.S. 1977. The selection of class +intervals. {it:Transactions of the Institute of British Geographers} +2: 98{c -}124. + +{p 4 8 2}Olson, J.M. 1976. Noncontiguous area +cartograms. {it:The Professional Geographer} 28: 371{c -}380. + +{p 4 8 2}Pisati, M. 2004. Simple thematic mapping. {it:The Stata Journal} 4: 361{c -}378. + +{p 4 8 2}Slocum, T.A., McMaster, R.B., Kessler, F.C and +H.H. Howard. 2005. {it:Thematic Cartography and Geographic Visualization}. 2nd +ed. Upper Saddle River: Pearson Prentice Hall. + + +{title:Also see} + +{psee} +Online: {helpb shp2dta} (if installed), {helpb mif2dta} (if installed) +{p_end} diff --git a/notebooks/msna/Codes/ado/s/spmap_arrow.ado b/notebooks/msna/Codes/ado/s/spmap_arrow.ado new file mode 100644 index 00000000..48b19015 --- /dev/null +++ b/notebooks/msna/Codes/ado/s/spmap_arrow.ado @@ -0,0 +1,555 @@ +*! -spmap_arrow-: Auxiliary program for -spmap- +*! Version 1.3.0 - 13 March 2017 +*! Version 1.2.0 - 14 March 2008 +*! Version 1.1.0 - 7 May 2007 +*! Version 1.0.0 - 7 December 2006 +*! Author: Maurizio Pisati +*! Department of Sociology and Social Research +*! University of Milano Bicocca (Italy) +*! maurizio.pisati@unimib.it + + + + +* ---------------------------------------------------------------------------- +* 1. Define program +* ---------------------------------------------------------------------------- + +program spmap_arrow, rclass +version 9.2 + + + + +* ---------------------------------------------------------------------------- +* 2. Define syntax +* ---------------------------------------------------------------------------- + +syntax, [Data(string)] /// + [Select(string asis)] /// + [BY(string)] /// + /// + [DIRection(string)] /// + [HSIze(string)] /// + [HANgle(string)] /// + [HBArbsize(string)] /// + [HFColor(string asis)] /// + [HOColor(string asis)] /// + [HOSize(string)] /// + [LCOlor(string asis)] /// + [LSIze(string)] /// + [LPAttern(string asis)] /// + /// + [LEGENDA(string)] /// + [LEGTitle(string asis)] /// + [LEGLabel(string)] /// + [LEGShow(string)] /// + [LEGCount] + + + + +* ---------------------------------------------------------------------------- +* 3. Check syntax +* ---------------------------------------------------------------------------- + +/* Preserve data */ +preserve + +/* Check and open dataset */ +if ("`data'" == "") { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: suboption " /// + "{bf:{ul:d}ata()} is required{p_end}" + exit 198 +} +if (substr(reverse("`data'"),1,4) != "atd.") { + local data "`data'.dta" +} +capture confirm file "`data'" +if _rc { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: file " /// + "{bf:`data'} specified in suboption {bf:{ul:d}ata()} " /// + "not found{p_end}" + exit 601 +} +use "`data'", clear +cap confirm numeric variable _ID _X1 _Y1 _X2 _Y2 +if _rc { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: file " /// + "{bf:`data'} specified in suboption {bf:{ul:d}ata()} " /// + "is not a valid {help spmap##sd_arrow:{it:arrow}} " /// + "dataset {p_end}" + exit 198 +} + +/* Select relevant records */ +if (`"`select'"' != "") { + cap `select' + if _rc { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: suboption " /// + "{bf:{ul:s}elect()} specified incorrectly{p_end}" + exit 198 + } +} + +/* Check option by() */ +if ("`by'" != "") { + cap unab by : `by' + if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: " /// + "variable {bf:`by'} specified in suboption " /// + "{bf:{ul:by}()} not found{p_end}" + exit 111 + } + if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: " /// + "string {bf:`by'} specified in suboption " /// + "{bf:{ul:by}()} is not a valid variable " /// + "name{p_end}" + exit 198 + } + local NW : word count `by' + if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: " /// + "suboption {bf:{ul:by}()} accepts only one " /// + "variable{p_end}" + exit 198 + } +} + +/* Check option direction() */ +if ("`direction'" != "") { + local NW : word count `direction' + forval i = 1/`NW' { + local W : word `i' of `direction' + if (!inlist("`W'",".","=","..","...")) { + cap confirm number `W' + if _rc { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:dir}ection()} accepts only " /// + "numbers{p_end}" + exit 7 + } + if (`W' < 1 | `W' > 2) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:dir}ection()} accepts only " /// + "one of the following arguments:{p_end}" + di as err "1 = Directional arrows" + di as err "2 = Bidirectional arrows" + exit 198 + } + } + } +} + +/* Check option legenda() */ +if ("`legenda'" != "") { + local LIST "on off" + local EXIST : list posof "`legenda'" in LIST + if !`EXIST' { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: " /// + "suboption {bf:{ul:legenda}()} accepts only one " /// + "of the following keywords: {bf:`LIST'}{p_end}" + exit 198 + } +} + +/* Check options relevant only when legenda(on) */ +if ("`legenda'" == "on") { + + /* Check option leglabel() */ + if (`"`leglabel'"' == "") & ("`by'" == "") { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: since " /// + "you have specified suboption {bf:{ul:legenda}(on)} " /// + "but you have not specified any group variable in " /// + "suboption {bf:{ul:by}()}, you are requested to " /// + "specify suboption {bf:{ul:legl}abel()}{p_end}" + exit 198 + } + + /* Check option legshow() */ + if ("`legshow'" != "") { + cap numlist "`legshow'" + if _rc { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: " /// + "invalid numlist in suboption " /// + "{bf:{ul:legs}how()}{p_end}" + exit 121 + } + } + +/* End */ +} + +/* Marksample */ +marksample TOUSE +if ("`by'" != "") markout `TOUSE' `by', strok +qui count if `TOUSE' +if (r(N) == 0) error 2000 + + + + +* ---------------------------------------------------------------------------- +* 4. Define basic objects +* ---------------------------------------------------------------------------- + +/* Select relevant observations */ +qui keep if `TOUSE' + +/* Set default arrow direction */ +local direction_d "1" +if ("`direction'" == "") local direction "`direction_d' ..." + +/* Set default arrowhead size */ +local hsize_d "1.5" +if ("`hsize'" == "") local hsize "`hsize_d' ..." + +/* Set default arrowhead angle */ +local hangle_d "28.64" +if ("`hangle'" == "") local hangle "`hangle_d' ..." + +/* Set default arrowhead barbsize (size of portion to be filled) */ +local hbarbsize_d "1.5" +if ("`hbarbsize'" == "") local hbarbsize "`hbarbsize_d' ..." + +/* Set default arrowhead fill color */ +local hfcolor_d "black" +if (`"`hfcolor'"' == "") local hfcolor "`hfcolor_d' ..." + +/* Set default arrowhead outline color */ +local hocolor_d "black" +if (`"`hocolor'"' == "") local hocolor "`hocolor_d' ..." + +/* Set default arrowhead outline thickness */ +local hosize_d "thin" +if ("`hosize'" == "") local hosize "`hosize_d' ..." + +/* Set default arrowline color */ +local lcolor_d "black" +if (`"`lcolor'"' == "") local lcolor "`lcolor_d' ..." + +/* Set default arrowline thickness */ +local lsize_d "thin" +if ("`lsize'" == "") local lsize "`lsize_d' ..." + +/* Set default arrowline pattern */ +local lpattern_d "solid" +if (`"`lpattern'"' == "") local lpattern "`lpattern_d' ..." + +/* Set default legend */ +if ("`legenda'" == "") local legenda "off" + +/* Set legend title when legtitle(varlab) */ +if ("`legenda'" == "on") & ("`by'" != "") & (`"`legtitle'"' == "varlab") { + local legtitle : variable label `by' + if (`"`legtitle'"' == "") local legtitle "`by'" +} + + + + +* ---------------------------------------------------------------------------- +* 5. Create working dataset +* ---------------------------------------------------------------------------- + +/* Housekeeping */ +cap drop __ARR* + +/* Generate group variable */ +if ("`by'" == "") qui gen __ARR_G = 1 +if ("`by'" != "") qui egen __ARR_G = group(`by'), lname(__ARR_G) +qui tab __ARR_G +local NG = r(r) + +/* Generate coordinate variables */ +qui gen __ARR_X1 = _X1 +qui gen __ARR_Y1 = _Y1 +qui gen __ARR_X2 = _X2 +qui gen __ARR_Y2 = _Y2 + +/* Count objects */ +if ("`legenda'" == "on") & ("`legcount'" != "") { + forval i = 1/`NG' { + qui tab _ID if __ARR_G == `i' + local COUNT "`COUNT'`r(r)' " + } +} + +/* Save dataset */ +keep __ARR* +qui save "__ARR.dta", replace + + + + +* ---------------------------------------------------------------------------- +* 6. Parse style lists +* ---------------------------------------------------------------------------- + +/* Set list of available color palettes */ +local PALETTE "`PALETTE' Accent Blues BrBG BuGn BuPu Dark2 GnBu Greens Greys" +local PALETTE "`PALETTE' OrRd Oranges PRGn Paired Pastel1 Pastel2 PiYG PuBu" +local PALETTE "`PALETTE' PuBuGn PuOr PuRd Purples RdBu RdGy RdPu RdYlBu" +local PALETTE "`PALETTE' RdYlGn Reds Set1 Set2 Set3 Spectral YlGn YlGnBu" +local PALETTE "`PALETTE' YlOrBr YlOrRd" +local PALETTE "`PALETTE' BuRd BuYlRd Heat Terrain Topological" +local PALETTE "`PALETTE' Blues2 Greens2 Greys2 Reds2 Rainbow" + +/* Parse option direction() */ +spmap_psl, l(`direction') m(`NG') o({bf:{ul:d}irection()}) d(`direction_d') +local direction `"`s(pl)'"' + +/* Parse option hsize() */ +spmap_psl, l(`hsize') m(`NG') o({bf:{ul:hsi}ze()}) d(`hsize_d') +local hsize `"`s(pl)'"' + +/* Parse option hangle() */ +spmap_psl, l(`hangle') m(`NG') o({bf:{ul:han}gle()}) d(`hangle_d') +local hangle `"`s(pl)'"' + +/* Parse option hbarbsize() */ +spmap_psl, l(`hbarbsize') m(`NG') o({bf:{ul:hba}rbsize()}) d(`hbarbsize_d') +local hbarbsize `"`s(pl)'"' + +/* Parse option hfcolor() */ +local EXIST : list posof `"`hfcolor'"' in PALETTE +if `EXIST' { + if (`NG' > 1) { + spmap_color "`hfcolor'" `NG' + local hfcolor `"`s(colors)'"' + } + else { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: " /// + "when no group variable is specified in suboption " /// + "{bf:{ul:by}()}, suboption {bf:{ul:hfc}olor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`hfcolor') m(`NG') o({bf:{ul:hfc}olor()}) d(`hfcolor_d') + local hfcolor `"`s(pl)'"' +} + +/* Parse option hocolor() */ +local EXIST : list posof `"`hocolor'"' in PALETTE +if `EXIST' { + if (`NG' > 1) { + spmap_color "`hocolor'" `NG' + local hocolor `"`s(colors)'"' + } + else { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: " /// + "when no group variable is specified in suboption " /// + "{bf:{ul:by}()}, suboption {bf:{ul:hoc}olor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`hocolor') m(`NG') o({bf:{ul:hoc}olor()}) d(`hocolor_d') + local hocolor `"`s(pl)'"' +} + +/* Parse option hosize() */ +spmap_psl, l(`hosize') m(`NG') o({bf:{ul:hos}ize()}) d(`hosize_d') +local hosize `"`s(pl)'"' + +/* Parse option lcolor() */ +local EXIST : list posof `"`lcolor'"' in PALETTE +if `EXIST' { + if (`NG' > 1) { + spmap_color "`lcolor'" `NG' + local lcolor `"`s(colors)'"' + } + else { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: " /// + "when no group variable is specified in suboption " /// + "{bf:{ul:by}()}, suboption {bf:{ul:lco}lor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`lcolor') m(`NG') o({bf:{ul:lco}lor()}) d(`lcolor_d') + local lcolor `"`s(pl)'"' +} + +/* Parse option lsize() */ +spmap_psl, l(`lsize') m(`NG') o({bf:{ul:lsi}ze()}) d(`lsize_d') +local lsize `"`s(pl)'"' + +/* Parse option lpattern() */ +spmap_psl, l(`lpattern') m(`NG') o({bf:{ul:lpa}ttern()}) d(`lpattern_d') +local lpattern `"`s(pl)'"' + + + + +* ---------------------------------------------------------------------------- +* 7. Compose command +* ---------------------------------------------------------------------------- + +/* Compose command */ +forval i = 1/`NG' { + local DIR : word `i' of `direction' + if (`DIR' == 1) local ARROW "pcarrow" + if (`DIR' == 2) local ARROW "pcbarrow" + local HSI : word `i' of `hsize' + local HAN : word `i' of `hangle' + local HBA : word `i' of `hbarbsize' + local HFC : word `i' of `hfcolor' + local HOC : word `i' of `hocolor' + if ("`HOC'" == "none") local HOC "`HFC'" + local HOS : word `i' of `hosize' + local LCO : word `i' of `lcolor' + local LSI : word `i' of `lsize' + local LPA : word `i' of `lpattern' + local GRAPH `"`GRAPH'(`ARROW' __ARR_Y1 __ARR_X1 __ARR_Y2 __ARR_X2"' + local GRAPH `"`GRAPH' if __ARR_G == `i', msize("`HSI'") mangle("`HAN'")"' + local GRAPH `"`GRAPH' barbsize("`HBA'") mfcolor("`HFC'") mlcolor("`HOC'")"' + local GRAPH `"`GRAPH' mlwidth("`HOS'") lcolor("`LCO'") lwidth("`LSI'")"' + local GRAPH `"`GRAPH' lpattern("`LPA'")) "' +} + + + + +* ---------------------------------------------------------------------------- +* 8. Set legend order and labels +* ---------------------------------------------------------------------------- + +/* Set number of keys */ +local NK = `NG' + + +/* legenda(off) */ +if ("`legenda'" == "off") { + local TITLE "" + local KEY "" + local LABEL "" +} + + +/* legenda(on) & by == "" */ +if ("`legenda'" == "on") & ("`by'" == "") { + + /* Title */ + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + + /* Keys */ + local KEY "1 " + + /* Labels */ + if ("`legcount'" == "") { + local LABEL `"`"`leglabel'"' "' + } + else { + local OBS : word 1 of `COUNT' + local LABEL `"`"`leglabel' (`OBS')"' "' + } + +/* End */ +} + + +/* legenda(on) & by == !" */ +if ("`legenda'" == "on") & ("`by'" != "") { + + /* Title */ + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + + /* Keys */ + if ("`legshow'" == "") { + numlist "1/`NK'" + local KEY "`r(numlist)'" + } + else { + qui levelsof __ARR_G, local (VL) + local CHECK : list legshow in VL + if !`CHECK' { + di as err "{p}Problem with option {bf:{ul:arr}ow()}: " /// + "one or more keys specified in suboption " /// + "{bf:{ul:legs}how()} do not exist. Valid keys " /// + " are: `VL'{p_end}" + exit 198 + } + else local KEY "`legshow'" + } + + /* Labels */ + foreach K in `KEY' { + local LBL : label (__ARR_G) `K' + if ("`legcount'" == "") { + local LABEL `"`LABEL'`"`LBL'"' "' + } + else { + local OBS : word `K' of `COUNT' + local LABEL `"`LABEL'`"`LBL' (`OBS')"' "' + } + } + +/* End */ +} + + + + +* ---------------------------------------------------------------------------- +* 9. Return info of interest +* ---------------------------------------------------------------------------- + +/* Return command */ +return local command `"`GRAPH'"' + +/* Return min/max coordinates */ +qui summ __ARR_X1 +local xmin1 = r(min) +local xmax1 = r(max) +qui summ __ARR_X2 +local xmin2 = r(min) +local xmax2 = r(max) +qui summ __ARR_Y1 +local ymin1 = r(min) +local ymax1 = r(max) +qui summ __ARR_Y2 +local ymin2 = r(min) +local ymax2 = r(max) +return local xmin = min(`xmin1' , `xmin2') +return local xmax = max(`xmax1' , `xmax2') +return local ymin = min(`ymin1' , `ymin2') +return local ymax = max(`ymax1' , `ymax2') + +/* Return legend info */ +return local title `"`TITLE'"' +return local key `"`KEY'"' +return local label `"`LABEL'"' +return local nk = `NK' + + + + +* ---------------------------------------------------------------------------- +* 10. End program +* ---------------------------------------------------------------------------- + +restore +end + + + diff --git a/notebooks/msna/Codes/ado/s/spmap_color.ado b/notebooks/msna/Codes/ado/s/spmap_color.ado new file mode 100644 index 00000000..e0b75825 --- /dev/null +++ b/notebooks/msna/Codes/ado/s/spmap_color.ado @@ -0,0 +1,2474 @@ +*! -spmap_color-: Auxiliary program for -spmap- +*! Version 1.3.0 - 13 March 2017 +*! Version 1.2.0 - 14 March 2008 +*! Version 1.1.0 - 7 May 2007 +*! Version 1.0.0 - 7 December 2006 +*! Author: Maurizio Pisati +*! Department of Sociology and Social Research +*! University of Milano Bicocca (Italy) +*! maurizio.pisati@unimib.it + + + + +* ---------------------------------------------------------------------------- +* 1. Define program +* ---------------------------------------------------------------------------- + +program spmap_color, sclass +version 9.2 +args PALETTE NC + + + + +* ---------------------------------------------------------------------------- +* 2. Get specified palette colors and return color list +* ---------------------------------------------------------------------------- + +preserve + +quietly { + + /* Predefined palettes */ + if (!inlist("`PALETTE'","Blues2","Greens2","Reds2","Greys2","Rainbow")) { + cap findfile "spmap_color.ado" + insheet palette levels maxlev class r g b using `"`r(fn)'"', tab clear + drop in 1/147 + keep if palette == "`PALETTE'" + su maxlev, mean + if (r(mean) < `NC') { + di as err "{p}Maximum number of colors for palette " /// + "{bf:`PALETTE'} is `r(mean)'{p_end}" + exit 198 + } + keep if levels == `NC' + tempname RGB + mkmat r g b, matrix(`RGB') + forval i = 1/`NC' { + local R = `RGB'[`i',1] + local G = `RGB'[`i',2] + local B = `RGB'[`i',3] + local COLORS `"`COLORS'"`R' `G' `B'" "' + } + } + + /* Other palettes */ + else { + + /* Palette Blues2 */ + if ("`PALETTE'" == "Blues2") { + tempname HSB + matrix `HSB' = J(`NC', 3, .) + forval i = 1/`NC' { + matrix `HSB'[`i', 1] = 208 + matrix `HSB'[`i', 2] = 20 + 80 * (`i' - 1) / (`NC' - 1) + matrix `HSB'[`i', 3] = 100 - 60 * (`i' - 1) / (`NC' - 1) + } + } + + /* Palette Greens2 */ + if ("`PALETTE'" == "Greens2") { + tempname HSB + matrix `HSB' = J(`NC', 3, .) + forval i = 1/`NC' { + matrix `HSB'[`i', 1] = 122 + 20 * (`i' - 1) / (`NC' - 1) + matrix `HSB'[`i', 2] = 20 + 80 * (`i' - 1) / (`NC' - 1) + matrix `HSB'[`i', 3] = 100 - 70 * (`i' - 1) / (`NC' - 1) + } + } + + /* Palette Reds2 */ + if ("`PALETTE'" == "Reds2") { + tempname HSB + matrix `HSB' = J(`NC', 3, .) + forval i = 1/`NC' { + local PROP = (`i' - 1) / (`NC' - 1) + matrix `HSB'[`i', 1] = 20 - 20 * (`i' - 1) / (`NC' - 1) + matrix `HSB'[`i', 2] = 20 + 80 * (`i' - 1) / (`NC' - 1) + if (`PROP' < 0.5) matrix `HSB'[`i', 3] = 100 + else matrix `HSB'[`i', 3] = 100 - /// + 60 * (((`i' - 1) / (`NC' - 1)) - (0.5)) / 0.5 + } + } + + /* Palette Greys2 */ + if ("`PALETTE'" == "Greys2") { + tempname HSB + matrix `HSB' = J(`NC', 3, 0) + forval i = 1/`NC' { + matrix `HSB'[`i', 3] = 88 - ((`i' - 1) * 88) / (`NC' - 1) + } + } + + /* Palette Rainbow */ + if ("`PALETTE'" == "Rainbow") { + tempname HSB + matrix `HSB' = J(`NC', 3, 100) + forval i = 1/`NC' { + matrix `HSB'[`i', 1] = 240 - ((`i' - 1) * 240) / (`NC' - 1) + } + } + + /* Convert HSB -> RGB */ + forval i = 1/`NC' { + local H = `HSB'[`i', 1] / 360 + local S = `HSB'[`i', 2] / 100 + local V = `HSB'[`i', 3] / 100 + local H = `H' * 6 + local V = trunc(min(`V' * 256, 255)) + local iH = trunc(`H') + local fH = `H' - `iH' + if (mod(`iH',2) == 0) local fH = 1 - `fH' + local M = round(`V' * (1 - `S')) + local N = round(`V' * (1 - (`S' * `fH'))) + if (`iH' == 1) { + local R = `N' + local G = `V' + local B = `M' + } + if (`iH' == 2) { + local R = `M' + local G = `V' + local B = `N' + } + if (`iH' == 3) { + local R = `M' + local G = `N' + local B = `V' + } + if (`iH' == 4) { + local R = `N' + local G = `M' + local B = `V' + } + if (`iH' == 5) { + local R = `V' + local G = `M' + local B = `N' + } + if (`iH' == 0) { + local R = `V' + local G = `N' + local B = `M' + } + local COLORS `"`COLORS'"`R' `G' `B'" "' + } + } +} + +sreturn local colors `"`COLORS'"' +restore + + + + +* ---------------------------------------------------------------------------- +* 3. End program +* ---------------------------------------------------------------------------- + +end +exit + + + + +* ---------------------------------------------------------------------------- +* Predefined color palettes +* ---------------------------------------------------------------------------- + +/* palette levels maxlev class r g b */ +Blues 2 9 1 158 202 225 +Blues 2 9 2 49 130 189 +Blues 3 9 1 222 235 247 +Blues 3 9 2 158 202 225 +Blues 3 9 3 49 130 189 +Blues 4 9 1 239 243 255 +Blues 4 9 2 189 215 231 +Blues 4 9 3 107 174 214 +Blues 4 9 4 33 113 181 +Blues 5 9 1 239 243 255 +Blues 5 9 2 189 215 231 +Blues 5 9 3 107 174 214 +Blues 5 9 4 49 130 189 +Blues 5 9 5 8 81 156 +Blues 6 9 1 239 243 255 +Blues 6 9 2 198 219 239 +Blues 6 9 3 158 202 225 +Blues 6 9 4 107 174 214 +Blues 6 9 5 49 130 189 +Blues 6 9 6 8 81 156 +Blues 7 9 1 239 243 255 +Blues 7 9 2 198 219 239 +Blues 7 9 3 158 202 225 +Blues 7 9 4 107 174 214 +Blues 7 9 5 66 146 198 +Blues 7 9 6 33 113 181 +Blues 7 9 7 8 69 148 +Blues 8 9 1 247 251 255 +Blues 8 9 2 222 235 247 +Blues 8 9 3 198 219 239 +Blues 8 9 4 158 202 225 +Blues 8 9 5 107 174 214 +Blues 8 9 6 66 146 198 +Blues 8 9 7 33 113 181 +Blues 8 9 8 8 69 148 +Blues 9 9 1 247 251 255 +Blues 9 9 2 222 235 247 +Blues 9 9 3 198 219 239 +Blues 9 9 4 158 202 225 +Blues 9 9 5 107 174 214 +Blues 9 9 6 66 146 198 +Blues 9 9 7 33 113 181 +Blues 9 9 8 8 81 156 +Blues 9 9 9 8 48 107 +BuGn 2 9 1 153 216 201 +BuGn 2 9 2 44 162 95 +BuGn 3 9 1 229 245 249 +BuGn 3 9 2 153 216 201 +BuGn 3 9 3 44 162 95 +BuGn 4 9 1 237 248 251 +BuGn 4 9 2 178 226 226 +BuGn 4 9 3 102 194 164 +BuGn 4 9 4 35 139 69 +BuGn 5 9 1 237 248 251 +BuGn 5 9 2 178 226 226 +BuGn 5 9 3 102 194 164 +BuGn 5 9 4 44 162 95 +BuGn 5 9 5 0 109 44 +BuGn 6 9 1 237 248 251 +BuGn 6 9 2 204 236 230 +BuGn 6 9 3 153 216 201 +BuGn 6 9 4 102 194 164 +BuGn 6 9 5 44 162 95 +BuGn 6 9 6 0 109 44 +BuGn 7 9 1 237 248 251 +BuGn 7 9 2 204 236 230 +BuGn 7 9 3 153 216 201 +BuGn 7 9 4 102 194 164 +BuGn 7 9 5 65 174 118 +BuGn 7 9 6 35 139 69 +BuGn 7 9 7 0 88 36 +BuGn 8 9 1 247 252 253 +BuGn 8 9 2 229 245 249 +BuGn 8 9 3 204 236 230 +BuGn 8 9 4 153 216 201 +BuGn 8 9 5 102 194 164 +BuGn 8 9 6 65 174 118 +BuGn 8 9 7 35 139 69 +BuGn 8 9 8 0 88 36 +BuGn 9 9 1 247 252 253 +BuGn 9 9 2 229 245 249 +BuGn 9 9 3 204 236 230 +BuGn 9 9 4 153 216 201 +BuGn 9 9 5 102 194 164 +BuGn 9 9 6 65 174 118 +BuGn 9 9 7 35 139 69 +BuGn 9 9 8 0 109 44 +BuGn 9 9 9 0 68 27 +BuPu 2 9 1 158 188 218 +BuPu 2 9 2 136 86 167 +BuPu 3 9 1 224 236 244 +BuPu 3 9 2 158 188 218 +BuPu 3 9 3 136 86 167 +BuPu 4 9 1 237 248 251 +BuPu 4 9 2 179 205 227 +BuPu 4 9 3 140 150 198 +BuPu 4 9 4 136 65 157 +BuPu 5 9 1 237 248 251 +BuPu 5 9 2 179 205 227 +BuPu 5 9 3 140 150 198 +BuPu 5 9 4 136 86 167 +BuPu 5 9 5 129 15 124 +BuPu 6 9 1 237 248 251 +BuPu 6 9 2 191 211 230 +BuPu 6 9 3 158 188 218 +BuPu 6 9 4 140 150 198 +BuPu 6 9 5 136 86 167 +BuPu 6 9 6 129 15 124 +BuPu 7 9 1 237 248 251 +BuPu 7 9 2 191 211 230 +BuPu 7 9 3 158 188 218 +BuPu 7 9 4 140 150 198 +BuPu 7 9 5 140 107 177 +BuPu 7 9 6 136 65 157 +BuPu 7 9 7 110 1 107 +BuPu 8 9 1 247 252 253 +BuPu 8 9 2 224 236 244 +BuPu 8 9 3 191 211 230 +BuPu 8 9 4 158 188 218 +BuPu 8 9 5 140 150 198 +BuPu 8 9 6 140 107 177 +BuPu 8 9 7 136 65 157 +BuPu 8 9 8 110 1 107 +BuPu 9 9 1 247 252 253 +BuPu 9 9 2 224 236 244 +BuPu 9 9 3 191 211 230 +BuPu 9 9 4 158 188 218 +BuPu 9 9 5 140 150 198 +BuPu 9 9 6 140 107 177 +BuPu 9 9 7 136 65 157 +BuPu 9 9 8 129 15 124 +BuPu 9 9 9 77 0 75 +GnBu 2 9 1 168 221 181 +GnBu 2 9 2 67 162 202 +GnBu 3 9 1 224 243 219 +GnBu 3 9 2 168 221 181 +GnBu 3 9 3 67 162 202 +GnBu 4 9 1 240 249 232 +GnBu 4 9 2 186 228 188 +GnBu 4 9 3 123 204 196 +GnBu 4 9 4 43 140 190 +GnBu 5 9 1 240 249 232 +GnBu 5 9 2 186 228 188 +GnBu 5 9 3 123 204 196 +GnBu 5 9 4 67 162 202 +GnBu 5 9 5 8 104 172 +GnBu 6 9 1 240 249 232 +GnBu 6 9 2 204 235 197 +GnBu 6 9 3 168 221 181 +GnBu 6 9 4 123 204 196 +GnBu 6 9 5 67 162 202 +GnBu 6 9 6 8 104 172 +GnBu 7 9 1 240 249 232 +GnBu 7 9 2 204 235 197 +GnBu 7 9 3 168 221 181 +GnBu 7 9 4 123 204 196 +GnBu 7 9 5 78 179 211 +GnBu 7 9 6 43 140 190 +GnBu 7 9 7 8 88 158 +GnBu 8 9 1 247 252 240 +GnBu 8 9 2 224 243 219 +GnBu 8 9 3 204 235 197 +GnBu 8 9 4 168 221 181 +GnBu 8 9 5 123 204 196 +GnBu 8 9 6 78 179 211 +GnBu 8 9 7 43 140 190 +GnBu 8 9 8 8 88 158 +GnBu 9 9 1 247 252 240 +GnBu 9 9 2 224 243 219 +GnBu 9 9 3 204 235 197 +GnBu 9 9 4 168 221 181 +GnBu 9 9 5 123 204 196 +GnBu 9 9 6 78 179 211 +GnBu 9 9 7 43 140 190 +GnBu 9 9 8 8 104 172 +GnBu 9 9 9 8 64 129 +Greens 2 9 1 161 217 155 +Greens 2 9 2 49 163 84 +Greens 3 9 1 229 245 224 +Greens 3 9 2 161 217 155 +Greens 3 9 3 49 163 84 +Greens 4 9 1 237 248 233 +Greens 4 9 2 186 228 179 +Greens 4 9 3 116 196 118 +Greens 4 9 4 35 139 69 +Greens 5 9 1 237 248 233 +Greens 5 9 2 186 228 179 +Greens 5 9 3 116 196 118 +Greens 5 9 4 49 163 84 +Greens 5 9 5 0 109 44 +Greens 6 9 1 237 248 233 +Greens 6 9 2 199 233 192 +Greens 6 9 3 161 217 155 +Greens 6 9 4 116 196 118 +Greens 6 9 5 49 163 84 +Greens 6 9 6 0 109 44 +Greens 7 9 1 237 248 233 +Greens 7 9 2 199 233 192 +Greens 7 9 3 161 217 155 +Greens 7 9 4 116 196 118 +Greens 7 9 5 65 171 93 +Greens 7 9 6 35 139 69 +Greens 7 9 7 0 90 50 +Greens 8 9 1 247 252 245 +Greens 8 9 2 229 245 224 +Greens 8 9 3 199 233 192 +Greens 8 9 4 161 217 155 +Greens 8 9 5 116 196 118 +Greens 8 9 6 65 171 93 +Greens 8 9 7 35 139 69 +Greens 8 9 8 0 90 50 +Greens 9 9 1 247 252 245 +Greens 9 9 2 229 245 224 +Greens 9 9 3 199 233 192 +Greens 9 9 4 161 217 155 +Greens 9 9 5 116 196 118 +Greens 9 9 6 65 171 93 +Greens 9 9 7 35 139 69 +Greens 9 9 8 0 109 44 +Greens 9 9 9 0 68 27 +Greys 2 9 1 189 189 189 +Greys 2 9 2 99 99 99 +Greys 3 9 1 240 240 240 +Greys 3 9 2 189 189 189 +Greys 3 9 3 99 99 99 +Greys 4 9 1 247 247 247 +Greys 4 9 2 204 204 204 +Greys 4 9 3 150 150 150 +Greys 4 9 4 82 82 82 +Greys 5 9 1 247 247 247 +Greys 5 9 2 204 204 204 +Greys 5 9 3 150 150 150 +Greys 5 9 4 99 99 99 +Greys 5 9 5 37 37 37 +Greys 6 9 1 247 247 247 +Greys 6 9 2 217 217 217 +Greys 6 9 3 189 189 189 +Greys 6 9 4 150 150 150 +Greys 6 9 5 99 99 99 +Greys 6 9 6 37 37 37 +Greys 7 9 1 247 247 247 +Greys 7 9 2 217 217 217 +Greys 7 9 3 189 189 189 +Greys 7 9 4 150 150 150 +Greys 7 9 5 115 115 115 +Greys 7 9 6 82 82 82 +Greys 7 9 7 37 37 37 +Greys 8 9 1 255 255 255 +Greys 8 9 2 240 240 240 +Greys 8 9 3 217 217 217 +Greys 8 9 4 189 189 189 +Greys 8 9 5 150 150 150 +Greys 8 9 6 115 115 115 +Greys 8 9 7 82 82 82 +Greys 8 9 8 37 37 37 +Greys 9 9 1 255 255 255 +Greys 9 9 2 240 240 240 +Greys 9 9 3 217 217 217 +Greys 9 9 4 189 189 189 +Greys 9 9 5 150 150 150 +Greys 9 9 6 115 115 115 +Greys 9 9 7 82 82 82 +Greys 9 9 8 37 37 37 +Greys 9 9 9 0 0 0 +Heat 2 16 1 255 255 0 +Heat 2 16 2 255 0 0 +Heat 3 16 1 255 255 0 +Heat 3 16 2 255 128 0 +Heat 3 16 3 255 0 0 +Heat 4 16 1 255 255 128 +Heat 4 16 2 255 255 0 +Heat 4 16 3 255 128 0 +Heat 4 16 4 255 0 0 +Heat 5 16 1 255 255 128 +Heat 5 16 2 255 255 0 +Heat 5 16 3 255 170 0 +Heat 5 16 4 255 85 0 +Heat 5 16 5 255 0 0 +Heat 6 16 1 255 255 128 +Heat 6 16 2 255 255 0 +Heat 6 16 3 255 191 0 +Heat 6 16 4 255 128 0 +Heat 6 16 5 255 64 0 +Heat 6 16 6 255 0 0 +Heat 7 16 1 255 255 128 +Heat 7 16 2 255 255 0 +Heat 7 16 3 255 204 0 +Heat 7 16 4 255 153 0 +Heat 7 16 5 255 102 0 +Heat 7 16 6 255 51 0 +Heat 7 16 7 255 0 0 +Heat 8 16 1 255 255 191 +Heat 8 16 2 255 255 64 +Heat 8 16 3 255 255 0 +Heat 8 16 4 255 204 0 +Heat 8 16 5 255 153 0 +Heat 8 16 6 255 102 0 +Heat 8 16 7 255 51 0 +Heat 8 16 8 255 0 0 +Heat 9 16 1 255 255 191 +Heat 9 16 2 255 255 64 +Heat 9 16 3 255 255 0 +Heat 9 16 4 255 213 0 +Heat 9 16 5 255 170 0 +Heat 9 16 6 255 128 0 +Heat 9 16 7 255 85 0 +Heat 9 16 8 255 42 0 +Heat 9 16 9 255 0 0 +Heat 10 16 1 255 255 191 +Heat 10 16 2 255 255 64 +Heat 10 16 3 255 255 0 +Heat 10 16 4 255 219 0 +Heat 10 16 5 255 182 0 +Heat 10 16 6 255 146 0 +Heat 10 16 7 255 109 0 +Heat 10 16 8 255 73 0 +Heat 10 16 9 255 36 0 +Heat 10 16 10 255 0 0 +Heat 11 16 1 255 255 191 +Heat 11 16 2 255 255 64 +Heat 11 16 3 255 255 0 +Heat 11 16 4 255 223 0 +Heat 11 16 5 255 191 0 +Heat 11 16 6 255 159 0 +Heat 11 16 7 255 128 0 +Heat 11 16 8 255 96 0 +Heat 11 16 9 255 64 0 +Heat 11 16 10 255 32 0 +Heat 11 16 11 255 0 0 +Heat 12 16 1 255 255 213 +Heat 12 16 2 255 255 128 +Heat 12 16 3 255 255 42 +Heat 12 16 4 255 255 0 +Heat 12 16 5 255 223 0 +Heat 12 16 6 255 191 0 +Heat 12 16 7 255 159 0 +Heat 12 16 8 255 128 0 +Heat 12 16 9 255 96 0 +Heat 12 16 10 255 64 0 +Heat 12 16 11 255 32 0 +Heat 12 16 12 255 0 0 +Heat 13 16 1 255 255 213 +Heat 13 16 2 255 255 128 +Heat 13 16 3 255 255 42 +Heat 13 16 4 255 255 0 +Heat 13 16 5 255 227 0 +Heat 13 16 6 255 198 0 +Heat 13 16 7 255 170 0 +Heat 13 16 8 255 142 0 +Heat 13 16 9 255 113 0 +Heat 13 16 10 255 85 0 +Heat 13 16 11 255 57 0 +Heat 13 16 12 255 28 0 +Heat 13 16 13 255 0 0 +Heat 14 16 1 255 255 213 +Heat 14 16 2 255 255 128 +Heat 14 16 3 255 255 42 +Heat 14 16 4 255 255 0 +Heat 14 16 5 255 229 0 +Heat 14 16 6 255 204 0 +Heat 14 16 7 255 178 0 +Heat 14 16 8 255 153 0 +Heat 14 16 9 255 128 0 +Heat 14 16 10 255 102 0 +Heat 14 16 11 255 77 0 +Heat 14 16 12 255 51 0 +Heat 14 16 13 255 26 0 +Heat 14 16 14 255 0 0 +Heat 15 16 1 255 255 213 +Heat 15 16 2 255 255 128 +Heat 15 16 3 255 255 42 +Heat 15 16 4 255 255 0 +Heat 15 16 5 255 232 0 +Heat 15 16 6 255 209 0 +Heat 15 16 7 255 185 0 +Heat 15 16 8 255 162 0 +Heat 15 16 9 255 139 0 +Heat 15 16 10 255 116 0 +Heat 15 16 11 255 93 0 +Heat 15 16 12 255 70 0 +Heat 15 16 13 255 46 0 +Heat 15 16 14 255 23 0 +Heat 15 16 15 255 0 0 +Heat 16 16 1 255 255 223 +Heat 16 16 2 255 255 159 +Heat 16 16 3 255 255 96 +Heat 16 16 4 255 255 32 +Heat 16 16 5 255 255 0 +Heat 16 16 6 255 232 0 +Heat 16 16 7 255 209 0 +Heat 16 16 8 255 185 0 +Heat 16 16 9 255 162 0 +Heat 16 16 10 255 139 0 +Heat 16 16 11 255 116 0 +Heat 16 16 12 255 93 0 +Heat 16 16 13 255 70 0 +Heat 16 16 14 255 46 0 +Heat 16 16 15 255 23 0 +Heat 16 16 16 255 0 0 +OrRd 2 9 1 253 187 132 +OrRd 2 9 2 227 74 51 +OrRd 3 9 1 254 232 200 +OrRd 3 9 2 253 187 132 +OrRd 3 9 3 227 74 51 +OrRd 4 9 1 254 240 217 +OrRd 4 9 2 253 204 138 +OrRd 4 9 3 252 141 89 +OrRd 4 9 4 215 48 31 +OrRd 5 9 1 254 240 217 +OrRd 5 9 2 253 204 138 +OrRd 5 9 3 252 141 89 +OrRd 5 9 4 227 74 51 +OrRd 5 9 5 179 0 0 +OrRd 6 9 1 254 240 217 +OrRd 6 9 2 253 212 158 +OrRd 6 9 3 253 187 132 +OrRd 6 9 4 252 141 89 +OrRd 6 9 5 227 74 51 +OrRd 6 9 6 179 0 0 +OrRd 7 9 1 254 240 217 +OrRd 7 9 2 253 212 158 +OrRd 7 9 3 253 187 132 +OrRd 7 9 4 252 141 89 +OrRd 7 9 5 239 101 72 +OrRd 7 9 6 215 48 31 +OrRd 7 9 7 153 0 0 +OrRd 8 9 1 255 247 236 +OrRd 8 9 2 254 232 200 +OrRd 8 9 3 253 212 158 +OrRd 8 9 4 253 187 132 +OrRd 8 9 5 252 141 89 +OrRd 8 9 6 239 101 72 +OrRd 8 9 7 215 48 31 +OrRd 8 9 8 153 0 0 +OrRd 9 9 1 255 247 236 +OrRd 9 9 2 254 232 200 +OrRd 9 9 3 253 212 158 +OrRd 9 9 4 253 187 132 +OrRd 9 9 5 252 141 89 +OrRd 9 9 6 239 101 72 +OrRd 9 9 7 215 48 31 +OrRd 9 9 8 179 0 0 +OrRd 9 9 9 127 0 0 +Oranges 2 9 1 253 174 107 +Oranges 2 9 2 230 85 13 +Oranges 3 9 1 254 230 206 +Oranges 3 9 2 253 174 107 +Oranges 3 9 3 230 85 13 +Oranges 4 9 1 254 237 222 +Oranges 4 9 2 253 190 133 +Oranges 4 9 3 253 141 60 +Oranges 4 9 4 217 71 1 +Oranges 5 9 1 254 237 222 +Oranges 5 9 2 253 190 133 +Oranges 5 9 3 253 141 60 +Oranges 5 9 4 230 85 13 +Oranges 5 9 5 166 54 3 +Oranges 6 9 1 254 237 222 +Oranges 6 9 2 253 208 162 +Oranges 6 9 3 253 174 107 +Oranges 6 9 4 253 141 60 +Oranges 6 9 5 230 85 13 +Oranges 6 9 6 166 54 3 +Oranges 7 9 1 254 237 222 +Oranges 7 9 2 253 208 162 +Oranges 7 9 3 253 174 107 +Oranges 7 9 4 253 141 60 +Oranges 7 9 5 241 105 19 +Oranges 7 9 6 217 72 1 +Oranges 7 9 7 140 45 4 +Oranges 8 9 1 255 245 235 +Oranges 8 9 2 254 230 206 +Oranges 8 9 3 253 208 162 +Oranges 8 9 4 253 174 107 +Oranges 8 9 5 253 141 60 +Oranges 8 9 6 241 105 19 +Oranges 8 9 7 217 72 1 +Oranges 8 9 8 140 45 4 +Oranges 9 9 1 255 245 235 +Oranges 9 9 2 254 230 206 +Oranges 9 9 3 253 208 162 +Oranges 9 9 4 253 174 107 +Oranges 9 9 5 253 141 60 +Oranges 9 9 6 241 105 19 +Oranges 9 9 7 217 72 1 +Oranges 9 9 8 166 54 3 +Oranges 9 9 9 127 39 4 +PuBu 2 9 1 166 189 219 +PuBu 2 9 2 43 140 190 +PuBu 3 9 1 236 231 242 +PuBu 3 9 2 166 189 219 +PuBu 3 9 3 43 140 190 +PuBu 4 9 1 241 238 246 +PuBu 4 9 2 189 201 225 +PuBu 4 9 3 116 169 207 +PuBu 4 9 4 5 112 176 +PuBu 5 9 1 241 238 246 +PuBu 5 9 2 189 201 225 +PuBu 5 9 3 116 169 207 +PuBu 5 9 4 43 140 190 +PuBu 5 9 5 4 90 141 +PuBu 6 9 1 241 238 246 +PuBu 6 9 2 208 209 230 +PuBu 6 9 3 166 189 219 +PuBu 6 9 4 116 169 207 +PuBu 6 9 5 43 140 190 +PuBu 6 9 6 4 90 141 +PuBu 7 9 1 241 238 246 +PuBu 7 9 2 208 209 230 +PuBu 7 9 3 166 189 219 +PuBu 7 9 4 116 169 207 +PuBu 7 9 5 54 144 192 +PuBu 7 9 6 5 112 176 +PuBu 7 9 7 3 78 123 +PuBu 8 9 1 255 247 251 +PuBu 8 9 2 236 231 242 +PuBu 8 9 3 208 209 230 +PuBu 8 9 4 166 189 219 +PuBu 8 9 5 116 169 207 +PuBu 8 9 6 54 144 192 +PuBu 8 9 7 5 112 176 +PuBu 8 9 8 3 78 123 +PuBu 9 9 1 255 247 251 +PuBu 9 9 2 236 231 242 +PuBu 9 9 3 208 209 230 +PuBu 9 9 4 166 189 219 +PuBu 9 9 5 116 169 207 +PuBu 9 9 6 54 144 192 +PuBu 9 9 7 5 112 176 +PuBu 9 9 8 4 90 141 +PuBu 9 9 9 2 56 88 +PuBuGn 2 9 1 166 189 219 +PuBuGn 2 9 2 28 144 153 +PuBuGn 3 9 1 236 226 240 +PuBuGn 3 9 2 166 189 219 +PuBuGn 3 9 3 28 144 153 +PuBuGn 4 9 1 246 239 247 +PuBuGn 4 9 2 189 201 225 +PuBuGn 4 9 3 103 169 207 +PuBuGn 4 9 4 2 129 138 +PuBuGn 5 9 1 246 239 247 +PuBuGn 5 9 2 189 201 225 +PuBuGn 5 9 3 103 169 207 +PuBuGn 5 9 4 28 144 153 +PuBuGn 5 9 5 1 108 89 +PuBuGn 6 9 1 246 239 247 +PuBuGn 6 9 2 208 209 230 +PuBuGn 6 9 3 166 189 219 +PuBuGn 6 9 4 103 169 207 +PuBuGn 6 9 5 28 144 153 +PuBuGn 6 9 6 1 108 89 +PuBuGn 7 9 1 246 239 247 +PuBuGn 7 9 2 208 209 230 +PuBuGn 7 9 3 166 189 219 +PuBuGn 7 9 4 103 169 207 +PuBuGn 7 9 5 54 144 192 +PuBuGn 7 9 6 2 129 138 +PuBuGn 7 9 7 1 100 80 +PuBuGn 8 9 1 255 247 251 +PuBuGn 8 9 2 236 226 240 +PuBuGn 8 9 3 208 209 230 +PuBuGn 8 9 4 166 189 219 +PuBuGn 8 9 5 103 169 207 +PuBuGn 8 9 6 54 144 192 +PuBuGn 8 9 7 2 129 138 +PuBuGn 8 9 8 1 100 80 +PuBuGn 9 9 1 255 247 251 +PuBuGn 9 9 2 236 226 240 +PuBuGn 9 9 3 208 209 230 +PuBuGn 9 9 4 166 189 219 +PuBuGn 9 9 5 103 169 207 +PuBuGn 9 9 6 54 144 192 +PuBuGn 9 9 7 2 129 138 +PuBuGn 9 9 8 1 108 89 +PuBuGn 9 9 9 1 70 54 +PuRd 2 9 1 201 148 199 +PuRd 2 9 2 221 28 119 +PuRd 3 9 1 231 225 239 +PuRd 3 9 2 201 148 199 +PuRd 3 9 3 221 28 119 +PuRd 4 9 1 241 238 246 +PuRd 4 9 2 215 181 216 +PuRd 4 9 3 223 101 176 +PuRd 4 9 4 206 18 86 +PuRd 5 9 1 241 238 246 +PuRd 5 9 2 215 181 216 +PuRd 5 9 3 223 101 176 +PuRd 5 9 4 221 28 119 +PuRd 5 9 5 152 0 67 +PuRd 6 9 1 241 238 246 +PuRd 6 9 2 212 185 218 +PuRd 6 9 3 201 148 199 +PuRd 6 9 4 223 101 176 +PuRd 6 9 5 221 28 119 +PuRd 6 9 6 152 0 67 +PuRd 7 9 1 241 238 246 +PuRd 7 9 2 212 185 218 +PuRd 7 9 3 201 148 199 +PuRd 7 9 4 223 101 176 +PuRd 7 9 5 231 41 138 +PuRd 7 9 6 206 18 86 +PuRd 7 9 7 145 0 63 +PuRd 8 9 1 247 244 249 +PuRd 8 9 2 231 225 239 +PuRd 8 9 3 212 185 218 +PuRd 8 9 4 201 148 199 +PuRd 8 9 5 223 101 176 +PuRd 8 9 6 231 41 138 +PuRd 8 9 7 206 18 86 +PuRd 8 9 8 145 0 63 +PuRd 9 9 1 247 244 249 +PuRd 9 9 2 231 225 239 +PuRd 9 9 3 212 185 218 +PuRd 9 9 4 201 148 199 +PuRd 9 9 5 223 101 176 +PuRd 9 9 6 231 41 138 +PuRd 9 9 7 206 18 86 +PuRd 9 9 8 152 0 67 +PuRd 9 9 9 103 0 31 +Purples 2 9 1 188 189 220 +Purples 2 9 2 117 107 177 +Purples 3 9 1 239 237 245 +Purples 3 9 2 188 189 220 +Purples 3 9 3 117 107 177 +Purples 4 9 1 242 240 247 +Purples 4 9 2 203 201 226 +Purples 4 9 3 158 154 200 +Purples 4 9 4 106 81 163 +Purples 5 9 1 242 240 247 +Purples 5 9 2 203 201 226 +Purples 5 9 3 158 154 200 +Purples 5 9 4 117 107 177 +Purples 5 9 5 84 39 143 +Purples 6 9 1 242 240 247 +Purples 6 9 2 218 218 235 +Purples 6 9 3 188 189 220 +Purples 6 9 4 158 154 200 +Purples 6 9 5 117 107 177 +Purples 6 9 6 84 39 143 +Purples 7 9 1 242 240 247 +Purples 7 9 2 218 218 235 +Purples 7 9 3 188 189 220 +Purples 7 9 4 158 154 200 +Purples 7 9 5 128 125 186 +Purples 7 9 6 106 81 163 +Purples 7 9 7 74 20 134 +Purples 8 9 1 252 251 253 +Purples 8 9 2 239 237 245 +Purples 8 9 3 218 218 235 +Purples 8 9 4 188 189 220 +Purples 8 9 5 158 154 200 +Purples 8 9 6 128 125 186 +Purples 8 9 7 106 81 163 +Purples 8 9 8 74 20 134 +Purples 9 9 1 252 251 253 +Purples 9 9 2 239 237 245 +Purples 9 9 3 218 218 235 +Purples 9 9 4 188 189 220 +Purples 9 9 5 158 154 200 +Purples 9 9 6 128 125 186 +Purples 9 9 7 106 81 163 +Purples 9 9 8 84 39 143 +Purples 9 9 9 63 0 125 +RdPu 2 9 1 250 159 181 +RdPu 2 9 2 197 27 138 +RdPu 3 9 1 253 224 221 +RdPu 3 9 2 250 159 181 +RdPu 3 9 3 197 27 138 +RdPu 4 9 1 254 235 226 +RdPu 4 9 2 251 180 185 +RdPu 4 9 3 247 104 161 +RdPu 4 9 4 174 1 126 +RdPu 5 9 1 254 235 226 +RdPu 5 9 2 251 180 185 +RdPu 5 9 3 247 104 161 +RdPu 5 9 4 197 27 138 +RdPu 5 9 5 122 1 119 +RdPu 6 9 1 254 235 226 +RdPu 6 9 2 252 197 192 +RdPu 6 9 3 250 159 181 +RdPu 6 9 4 247 104 161 +RdPu 6 9 5 197 27 138 +RdPu 6 9 6 122 1 119 +RdPu 7 9 1 254 235 226 +RdPu 7 9 2 252 197 192 +RdPu 7 9 3 250 159 181 +RdPu 7 9 4 247 104 161 +RdPu 7 9 5 221 52 151 +RdPu 7 9 6 174 1 126 +RdPu 7 9 7 122 1 119 +RdPu 8 9 1 255 247 243 +RdPu 8 9 2 253 224 221 +RdPu 8 9 3 252 197 192 +RdPu 8 9 4 250 159 181 +RdPu 8 9 5 247 104 161 +RdPu 8 9 6 221 52 151 +RdPu 8 9 7 174 1 126 +RdPu 8 9 8 122 1 119 +RdPu 9 9 1 255 247 243 +RdPu 9 9 2 253 224 221 +RdPu 9 9 3 252 197 192 +RdPu 9 9 4 250 159 181 +RdPu 9 9 5 247 104 161 +RdPu 9 9 6 221 52 151 +RdPu 9 9 7 174 1 126 +RdPu 9 9 8 122 1 119 +RdPu 9 9 9 73 0 106 +Reds 2 9 1 252 146 114 +Reds 2 9 2 222 45 38 +Reds 3 9 1 254 224 210 +Reds 3 9 2 252 146 114 +Reds 3 9 3 222 45 38 +Reds 4 9 1 254 229 217 +Reds 4 9 2 252 174 145 +Reds 4 9 3 251 106 74 +Reds 4 9 4 203 24 29 +Reds 5 9 1 254 229 217 +Reds 5 9 2 252 174 145 +Reds 5 9 3 251 106 74 +Reds 5 9 4 222 45 38 +Reds 5 9 5 165 15 21 +Reds 6 9 1 254 229 217 +Reds 6 9 2 252 187 161 +Reds 6 9 3 252 146 114 +Reds 6 9 4 251 106 74 +Reds 6 9 5 222 45 38 +Reds 6 9 6 165 15 21 +Reds 7 9 1 254 229 217 +Reds 7 9 2 252 187 161 +Reds 7 9 3 252 146 114 +Reds 7 9 4 251 106 74 +Reds 7 9 5 239 59 44 +Reds 7 9 6 203 24 29 +Reds 7 9 7 153 0 13 +Reds 8 9 1 255 245 240 +Reds 8 9 2 254 224 210 +Reds 8 9 3 252 187 161 +Reds 8 9 4 252 146 114 +Reds 8 9 5 251 106 74 +Reds 8 9 6 239 59 44 +Reds 8 9 7 203 24 29 +Reds 8 9 8 153 0 13 +Reds 9 9 1 255 245 240 +Reds 9 9 2 254 224 210 +Reds 9 9 3 252 187 161 +Reds 9 9 4 252 146 114 +Reds 9 9 5 251 106 74 +Reds 9 9 6 239 59 44 +Reds 9 9 7 203 24 29 +Reds 9 9 8 165 15 21 +Reds 9 9 9 103 0 13 +Terrain 2 16 1 0 166 0 +Terrain 2 16 2 242 242 242 +Terrain 3 16 1 0 166 0 +Terrain 3 16 2 236 177 118 +Terrain 3 16 3 242 242 242 +Terrain 4 16 1 0 166 0 +Terrain 4 16 2 230 230 0 +Terrain 4 16 3 236 177 118 +Terrain 4 16 4 242 242 242 +Terrain 5 16 1 0 166 0 +Terrain 5 16 2 230 230 0 +Terrain 5 16 3 234 182 78 +Terrain 5 16 4 238 185 159 +Terrain 5 16 5 242 242 242 +Terrain 6 16 1 0 166 0 +Terrain 6 16 2 99 198 0 +Terrain 6 16 3 230 230 0 +Terrain 6 16 4 234 182 78 +Terrain 6 16 5 238 185 159 +Terrain 6 16 6 242 242 242 +Terrain 7 16 1 0 166 0 +Terrain 7 16 2 99 198 0 +Terrain 7 16 3 230 230 0 +Terrain 7 16 4 233 189 58 +Terrain 7 16 5 236 177 118 +Terrain 7 16 6 239 194 179 +Terrain 7 16 7 242 242 242 +Terrain 8 16 1 0 166 0 +Terrain 8 16 2 62 187 0 +Terrain 8 16 3 139 208 0 +Terrain 8 16 4 230 230 0 +Terrain 8 16 5 233 189 58 +Terrain 8 16 6 236 177 118 +Terrain 8 16 7 239 194 179 +Terrain 8 16 8 242 242 242 +Terrain 9 16 1 0 166 0 +Terrain 9 16 2 62 187 0 +Terrain 9 16 3 139 208 0 +Terrain 9 16 4 230 230 0 +Terrain 9 16 5 232 195 46 +Terrain 9 16 6 235 178 94 +Terrain 9 16 7 237 180 142 +Terrain 9 16 8 240 201 192 +Terrain 9 16 9 242 242 242 +Terrain 10 16 1 0 166 0 +Terrain 10 16 2 45 182 0 +Terrain 10 16 3 99 198 0 +Terrain 10 16 4 160 214 0 +Terrain 10 16 5 230 230 0 +Terrain 10 16 6 232 195 46 +Terrain 10 16 7 235 178 94 +Terrain 10 16 8 237 180 142 +Terrain 10 16 9 240 201 192 +Terrain 10 16 10 242 242 242 +Terrain 11 16 1 0 166 0 +Terrain 11 16 2 45 182 0 +Terrain 11 16 3 99 198 0 +Terrain 11 16 4 160 214 0 +Terrain 11 16 5 230 230 0 +Terrain 11 16 6 232 199 39 +Terrain 11 16 7 234 182 78 +Terrain 11 16 8 236 177 118 +Terrain 11 16 9 238 185 159 +Terrain 11 16 10 240 207 200 +Terrain 11 16 11 242 242 242 +Terrain 12 16 1 0 166 0 +Terrain 12 16 2 36 179 0 +Terrain 12 16 3 76 191 0 +Terrain 12 16 4 122 204 0 +Terrain 12 16 5 173 217 0 +Terrain 12 16 6 230 230 0 +Terrain 12 16 7 232 199 39 +Terrain 12 16 8 234 182 78 +Terrain 12 16 9 236 177 118 +Terrain 12 16 10 238 185 159 +Terrain 12 16 11 240 207 200 +Terrain 12 16 12 242 242 242 +Terrain 13 16 1 0 166 0 +Terrain 13 16 2 36 179 0 +Terrain 13 16 3 76 191 0 +Terrain 13 16 4 122 204 0 +Terrain 13 16 5 173 217 0 +Terrain 13 16 6 230 230 0 +Terrain 13 16 7 231 203 33 +Terrain 13 16 8 233 186 67 +Terrain 13 16 9 235 177 101 +Terrain 13 16 10 237 179 135 +Terrain 13 16 11 239 190 170 +Terrain 13 16 12 240 211 206 +Terrain 13 16 13 242 242 242 +Terrain 14 16 1 0 166 0 +Terrain 14 16 2 29 176 0 +Terrain 14 16 3 62 187 0 +Terrain 14 16 4 99 198 0 +Terrain 14 16 5 139 208 0 +Terrain 14 16 6 182 219 0 +Terrain 14 16 7 230 230 0 +Terrain 14 16 8 231 203 33 +Terrain 14 16 9 233 186 67 +Terrain 14 16 10 235 177 101 +Terrain 14 16 11 237 179 135 +Terrain 14 16 12 239 190 170 +Terrain 14 16 13 240 211 206 +Terrain 14 16 14 242 242 242 +Terrain 15 16 1 0 166 0 +Terrain 15 16 2 29 176 0 +Terrain 15 16 3 62 187 0 +Terrain 15 16 4 99 198 0 +Terrain 15 16 5 139 208 0 +Terrain 15 16 6 182 219 0 +Terrain 15 16 7 230 230 0 +Terrain 15 16 8 231 206 29 +Terrain 15 16 9 233 189 58 +Terrain 15 16 10 234 179 88 +Terrain 15 16 11 236 177 118 +Terrain 15 16 12 237 182 148 +Terrain 15 16 13 239 194 179 +Terrain 15 16 14 241 214 211 +Terrain 15 16 15 242 242 242 +Terrain 16 16 1 0 166 0 +Terrain 16 16 2 25 175 0 +Terrain 16 16 3 53 184 0 +Terrain 16 16 4 83 193 0 +Terrain 16 16 5 116 202 0 +Terrain 16 16 6 151 211 0 +Terrain 16 16 7 189 220 0 +Terrain 16 16 8 230 230 0 +Terrain 16 16 9 231 206 29 +Terrain 16 16 10 233 189 58 +Terrain 16 16 11 234 179 88 +Terrain 16 16 12 236 177 118 +Terrain 16 16 13 237 182 148 +Terrain 16 16 14 239 194 179 +Terrain 16 16 15 241 214 211 +Terrain 16 16 16 242 242 242 +Topological 2 16 1 76 0 255 +Topological 2 16 2 0 229 255 +Topological 3 16 1 76 0 255 +Topological 3 16 2 0 255 77 +Topological 3 16 3 255 255 0 +Topological 4 16 1 76 0 255 +Topological 4 16 2 0 229 255 +Topological 4 16 3 0 255 77 +Topological 4 16 4 255 255 0 +Topological 5 16 1 76 0 255 +Topological 5 16 2 0 76 255 +Topological 5 16 3 0 229 255 +Topological 5 16 4 0 255 77 +Topological 5 16 5 255 255 0 +Topological 6 16 1 76 0 255 +Topological 6 16 2 0 229 255 +Topological 6 16 3 0 255 77 +Topological 6 16 4 230 255 0 +Topological 6 16 5 255 255 0 +Topological 6 16 6 255 224 178 +Topological 7 16 1 76 0 255 +Topological 7 16 2 0 76 255 +Topological 7 16 3 0 229 255 +Topological 7 16 4 0 255 77 +Topological 7 16 5 230 255 0 +Topological 7 16 6 255 255 0 +Topological 7 16 7 255 224 178 +Topological 8 16 1 76 0 255 +Topological 8 16 2 0 25 255 +Topological 8 16 3 0 128 255 +Topological 8 16 4 0 229 255 +Topological 8 16 5 0 255 77 +Topological 8 16 6 230 255 0 +Topological 8 16 7 255 255 0 +Topological 8 16 8 255 224 178 +Topological 9 16 1 76 0 255 +Topological 9 16 2 0 76 255 +Topological 9 16 3 0 229 255 +Topological 9 16 4 0 255 77 +Topological 9 16 5 77 255 0 +Topological 9 16 6 230 255 0 +Topological 9 16 7 255 255 0 +Topological 9 16 8 255 222 89 +Topological 9 16 9 255 224 178 +Topological 10 16 1 76 0 255 +Topological 10 16 2 0 25 255 +Topological 10 16 3 0 128 255 +Topological 10 16 4 0 229 255 +Topological 10 16 5 0 255 77 +Topological 10 16 6 77 255 0 +Topological 10 16 7 230 255 0 +Topological 10 16 8 255 255 0 +Topological 10 16 9 255 222 89 +Topological 10 16 10 255 224 178 +Topological 11 16 1 76 0 255 +Topological 11 16 2 0 0 255 +Topological 11 16 3 0 76 255 +Topological 11 16 4 0 153 255 +Topological 11 16 5 0 229 255 +Topological 11 16 6 0 255 77 +Topological 11 16 7 77 255 0 +Topological 11 16 8 230 255 0 +Topological 11 16 9 255 255 0 +Topological 11 16 10 255 222 89 +Topological 11 16 11 255 224 178 +Topological 12 16 1 76 0 255 +Topological 12 16 2 0 25 255 +Topological 12 16 3 0 128 255 +Topological 12 16 4 0 229 255 +Topological 12 16 5 0 255 77 +Topological 12 16 6 26 255 0 +Topological 12 16 7 128 255 0 +Topological 12 16 8 230 255 0 +Topological 12 16 9 255 255 0 +Topological 12 16 10 255 229 59 +Topological 12 16 11 255 219 119 +Topological 12 16 12 255 224 178 +Topological 13 16 1 76 0 255 +Topological 13 16 2 0 0 255 +Topological 13 16 3 0 76 255 +Topological 13 16 4 0 153 255 +Topological 13 16 5 0 229 255 +Topological 13 16 6 0 255 77 +Topological 13 16 7 26 255 0 +Topological 13 16 8 128 255 0 +Topological 13 16 9 230 255 0 +Topological 13 16 10 255 255 0 +Topological 13 16 11 255 229 59 +Topological 13 16 12 255 219 119 +Topological 13 16 13 255 224 178 +Topological 14 16 1 76 0 255 +Topological 14 16 2 15 0 255 +Topological 14 16 3 0 46 255 +Topological 14 16 4 0 107 255 +Topological 14 16 5 0 168 255 +Topological 14 16 6 0 229 255 +Topological 14 16 7 0 255 77 +Topological 14 16 8 26 255 0 +Topological 14 16 9 128 255 0 +Topological 14 16 10 230 255 0 +Topological 14 16 11 255 255 0 +Topological 14 16 12 255 229 59 +Topological 14 16 13 255 219 119 +Topological 14 16 14 255 224 178 +Topological 15 16 1 76 0 255 +Topological 15 16 2 0 0 255 +Topological 15 16 3 0 76 255 +Topological 15 16 4 0 153 255 +Topological 15 16 5 0 229 255 +Topological 15 16 6 0 255 77 +Topological 15 16 7 0 255 0 +Topological 15 16 8 77 255 0 +Topological 15 16 9 153 255 0 +Topological 15 16 10 230 255 0 +Topological 15 16 11 255 255 0 +Topological 15 16 12 255 234 45 +Topological 15 16 13 255 222 89 +Topological 15 16 14 255 219 134 +Topological 15 16 15 255 224 178 +Topological 16 16 1 76 0 255 +Topological 16 16 2 15 0 255 +Topological 16 16 3 0 46 255 +Topological 16 16 4 0 107 255 +Topological 16 16 5 0 168 255 +Topological 16 16 6 0 229 255 +Topological 16 16 7 0 255 77 +Topological 16 16 8 0 255 0 +Topological 16 16 9 77 255 0 +Topological 16 16 10 153 255 0 +Topological 16 16 11 230 255 0 +Topological 16 16 12 255 255 0 +Topological 16 16 13 255 234 45 +Topological 16 16 14 255 222 89 +Topological 16 16 15 255 219 134 +Topological 16 16 16 255 224 178 +YlGn 2 9 1 173 221 142 +YlGn 2 9 2 49 163 84 +YlGn 3 9 1 247 252 185 +YlGn 3 9 2 173 221 142 +YlGn 3 9 3 49 163 84 +YlGn 4 9 1 255 255 204 +YlGn 4 9 2 194 230 153 +YlGn 4 9 3 120 198 121 +YlGn 4 9 4 35 132 67 +YlGn 5 9 1 255 255 204 +YlGn 5 9 2 194 230 153 +YlGn 5 9 3 120 198 121 +YlGn 5 9 4 49 163 84 +YlGn 5 9 5 0 104 55 +YlGn 6 9 1 255 255 204 +YlGn 6 9 2 217 240 163 +YlGn 6 9 3 173 221 142 +YlGn 6 9 4 120 198 121 +YlGn 6 9 5 49 163 84 +YlGn 6 9 6 0 104 55 +YlGn 7 9 1 255 255 204 +YlGn 7 9 2 217 240 163 +YlGn 7 9 3 173 221 142 +YlGn 7 9 4 120 198 121 +YlGn 7 9 5 65 171 93 +YlGn 7 9 6 35 132 67 +YlGn 7 9 7 0 90 50 +YlGn 8 9 1 255 255 229 +YlGn 8 9 2 247 252 185 +YlGn 8 9 3 217 240 163 +YlGn 8 9 4 173 221 142 +YlGn 8 9 5 120 198 121 +YlGn 8 9 6 65 171 93 +YlGn 8 9 7 35 132 67 +YlGn 8 9 8 0 90 50 +YlGn 9 9 1 255 255 229 +YlGn 9 9 2 247 252 185 +YlGn 9 9 3 217 240 163 +YlGn 9 9 4 173 221 142 +YlGn 9 9 5 120 198 121 +YlGn 9 9 6 65 171 93 +YlGn 9 9 7 35 132 67 +YlGn 9 9 8 0 104 55 +YlGn 9 9 9 0 69 41 +YlGnBu 2 9 1 127 205 187 +YlGnBu 2 9 2 44 127 184 +YlGnBu 3 9 1 237 248 177 +YlGnBu 3 9 2 127 205 187 +YlGnBu 3 9 3 44 127 184 +YlGnBu 4 9 1 255 255 204 +YlGnBu 4 9 2 161 218 180 +YlGnBu 4 9 3 65 182 196 +YlGnBu 4 9 4 34 94 168 +YlGnBu 5 9 1 255 255 204 +YlGnBu 5 9 2 161 218 180 +YlGnBu 5 9 3 65 182 196 +YlGnBu 5 9 4 44 127 184 +YlGnBu 5 9 5 37 52 148 +YlGnBu 6 9 1 255 255 204 +YlGnBu 6 9 2 199 233 180 +YlGnBu 6 9 3 127 205 187 +YlGnBu 6 9 4 65 182 196 +YlGnBu 6 9 5 44 127 184 +YlGnBu 6 9 6 37 52 148 +YlGnBu 7 9 1 255 255 204 +YlGnBu 7 9 2 199 233 180 +YlGnBu 7 9 3 127 205 187 +YlGnBu 7 9 4 65 182 196 +YlGnBu 7 9 5 29 145 192 +YlGnBu 7 9 6 34 94 168 +YlGnBu 7 9 7 12 44 132 +YlGnBu 8 9 1 255 255 217 +YlGnBu 8 9 2 237 248 177 +YlGnBu 8 9 3 199 233 180 +YlGnBu 8 9 4 127 205 187 +YlGnBu 8 9 5 65 182 196 +YlGnBu 8 9 6 29 145 192 +YlGnBu 8 9 7 34 94 168 +YlGnBu 8 9 8 12 44 132 +YlGnBu 9 9 1 255 255 217 +YlGnBu 9 9 2 237 248 177 +YlGnBu 9 9 3 199 233 180 +YlGnBu 9 9 4 127 205 187 +YlGnBu 9 9 5 65 182 196 +YlGnBu 9 9 6 29 145 192 +YlGnBu 9 9 7 34 94 168 +YlGnBu 9 9 8 37 52 148 +YlGnBu 9 9 9 8 29 88 +YlOrBr 2 9 1 254 196 79 +YlOrBr 2 9 2 217 95 14 +YlOrBr 3 9 1 255 247 188 +YlOrBr 3 9 2 254 196 79 +YlOrBr 3 9 3 217 95 14 +YlOrBr 4 9 1 255 255 212 +YlOrBr 4 9 2 254 217 142 +YlOrBr 4 9 3 254 153 41 +YlOrBr 4 9 4 204 76 2 +YlOrBr 5 9 1 255 255 212 +YlOrBr 5 9 2 254 217 142 +YlOrBr 5 9 3 254 153 41 +YlOrBr 5 9 4 217 95 14 +YlOrBr 5 9 5 153 52 4 +YlOrBr 6 9 1 255 255 212 +YlOrBr 6 9 2 254 227 145 +YlOrBr 6 9 3 254 196 79 +YlOrBr 6 9 4 254 153 41 +YlOrBr 6 9 5 217 95 14 +YlOrBr 6 9 6 153 52 4 +YlOrBr 7 9 1 255 255 212 +YlOrBr 7 9 2 254 227 145 +YlOrBr 7 9 3 254 196 79 +YlOrBr 7 9 4 254 153 41 +YlOrBr 7 9 5 236 112 20 +YlOrBr 7 9 6 204 76 2 +YlOrBr 7 9 7 140 45 4 +YlOrBr 8 9 1 255 255 229 +YlOrBr 8 9 2 255 247 188 +YlOrBr 8 9 3 254 227 145 +YlOrBr 8 9 4 254 196 79 +YlOrBr 8 9 5 254 153 41 +YlOrBr 8 9 6 236 112 20 +YlOrBr 8 9 7 204 76 2 +YlOrBr 8 9 8 140 45 4 +YlOrBr 9 9 1 255 255 229 +YlOrBr 9 9 2 255 247 188 +YlOrBr 9 9 3 254 227 145 +YlOrBr 9 9 4 254 196 79 +YlOrBr 9 9 5 254 153 41 +YlOrBr 9 9 6 236 112 20 +YlOrBr 9 9 7 204 76 2 +YlOrBr 9 9 8 153 52 4 +YlOrBr 9 9 9 102 37 6 +YlOrRd 2 9 1 254 178 76 +YlOrRd 2 9 2 240 59 32 +YlOrRd 3 9 1 255 237 160 +YlOrRd 3 9 2 254 178 76 +YlOrRd 3 9 3 240 59 32 +YlOrRd 4 9 1 255 255 178 +YlOrRd 4 9 2 254 204 92 +YlOrRd 4 9 3 253 141 60 +YlOrRd 4 9 4 227 26 28 +YlOrRd 5 9 1 255 255 178 +YlOrRd 5 9 2 254 204 92 +YlOrRd 5 9 3 253 141 60 +YlOrRd 5 9 4 240 59 32 +YlOrRd 5 9 5 189 0 38 +YlOrRd 6 9 1 255 255 178 +YlOrRd 6 9 2 254 217 118 +YlOrRd 6 9 3 254 178 76 +YlOrRd 6 9 4 253 141 60 +YlOrRd 6 9 5 240 59 32 +YlOrRd 6 9 6 189 0 38 +YlOrRd 7 9 1 255 255 178 +YlOrRd 7 9 2 254 217 118 +YlOrRd 7 9 3 254 178 76 +YlOrRd 7 9 4 253 141 60 +YlOrRd 7 9 5 252 78 42 +YlOrRd 7 9 6 227 26 28 +YlOrRd 7 9 7 177 0 38 +YlOrRd 8 9 1 255 255 204 +YlOrRd 8 9 2 255 237 160 +YlOrRd 8 9 3 254 217 118 +YlOrRd 8 9 4 254 178 76 +YlOrRd 8 9 5 253 141 60 +YlOrRd 8 9 6 252 78 42 +YlOrRd 8 9 7 227 26 28 +YlOrRd 8 9 8 177 0 38 +YlOrRd 9 9 1 255 255 204 +YlOrRd 9 9 2 255 237 160 +YlOrRd 9 9 3 254 217 118 +YlOrRd 9 9 4 254 178 76 +YlOrRd 9 9 5 253 141 60 +YlOrRd 9 9 6 252 78 42 +YlOrRd 9 9 7 227 26 28 +YlOrRd 9 9 8 189 0 38 +YlOrRd 9 9 9 128 0 38 +BrBG 2 11 1 216 179 101 +BrBG 2 11 2 90 180 172 +BrBG 3 11 1 216 179 101 +BrBG 3 11 2 245 245 245 +BrBG 3 11 3 90 180 172 +BrBG 4 11 1 166 97 26 +BrBG 4 11 2 223 194 125 +BrBG 4 11 3 128 205 193 +BrBG 4 11 4 1 133 113 +BrBG 5 11 1 166 97 26 +BrBG 5 11 2 223 194 125 +BrBG 5 11 3 245 245 245 +BrBG 5 11 4 128 205 193 +BrBG 5 11 5 1 133 113 +BrBG 6 11 1 140 81 10 +BrBG 6 11 2 216 179 101 +BrBG 6 11 3 246 232 195 +BrBG 6 11 4 199 234 229 +BrBG 6 11 5 90 180 172 +BrBG 6 11 6 1 102 94 +BrBG 7 11 1 140 81 10 +BrBG 7 11 2 216 179 101 +BrBG 7 11 3 246 232 195 +BrBG 7 11 4 245 245 245 +BrBG 7 11 5 199 234 229 +BrBG 7 11 6 90 180 172 +BrBG 7 11 7 1 102 94 +BrBG 8 11 1 140 81 10 +BrBG 8 11 2 191 129 45 +BrBG 8 11 3 223 194 125 +BrBG 8 11 4 246 232 195 +BrBG 8 11 5 199 234 229 +BrBG 8 11 6 128 205 193 +BrBG 8 11 7 53 151 143 +BrBG 8 11 8 1 102 94 +BrBG 9 11 1 140 81 10 +BrBG 9 11 2 191 129 45 +BrBG 9 11 3 223 194 125 +BrBG 9 11 4 246 232 195 +BrBG 9 11 5 245 245 245 +BrBG 9 11 6 199 234 229 +BrBG 9 11 7 128 205 193 +BrBG 9 11 8 53 151 143 +BrBG 9 11 9 1 102 94 +BrBG 10 11 1 84 48 5 +BrBG 10 11 2 140 81 10 +BrBG 10 11 3 191 129 45 +BrBG 10 11 4 223 194 125 +BrBG 10 11 5 246 232 195 +BrBG 10 11 6 199 234 229 +BrBG 10 11 7 128 205 193 +BrBG 10 11 8 53 151 143 +BrBG 10 11 9 1 102 94 +BrBG 10 11 10 0 60 48 +BrBG 11 11 1 84 48 5 +BrBG 11 11 2 140 81 10 +BrBG 11 11 3 191 129 45 +BrBG 11 11 4 223 194 125 +BrBG 11 11 5 246 232 195 +BrBG 11 11 6 245 245 245 +BrBG 11 11 7 199 234 229 +BrBG 11 11 8 128 205 193 +BrBG 11 11 9 53 151 143 +BrBG 11 11 10 1 102 94 +BrBG 11 11 11 0 60 48 +BuRd 2 11 1 103 169 207 +BuRd 2 11 2 239 138 98 +BuRd 3 11 1 103 169 207 +BuRd 3 11 2 247 247 247 +BuRd 3 11 3 239 138 98 +BuRd 4 11 1 5 113 176 +BuRd 4 11 2 146 197 222 +BuRd 4 11 3 244 165 130 +BuRd 4 11 4 202 0 32 +BuRd 5 11 1 5 113 176 +BuRd 5 11 2 146 197 222 +BuRd 5 11 3 247 247 247 +BuRd 5 11 4 244 165 130 +BuRd 5 11 5 202 0 32 +BuRd 6 11 1 33 102 172 +BuRd 6 11 2 103 169 207 +BuRd 6 11 3 209 229 240 +BuRd 6 11 4 253 219 199 +BuRd 6 11 5 239 138 98 +BuRd 6 11 6 178 24 43 +BuRd 7 11 1 33 102 172 +BuRd 7 11 2 103 169 207 +BuRd 7 11 3 209 229 240 +BuRd 7 11 4 247 247 247 +BuRd 7 11 5 253 219 199 +BuRd 7 11 6 239 138 98 +BuRd 7 11 7 178 24 43 +BuRd 8 11 1 33 102 172 +BuRd 8 11 2 67 147 195 +BuRd 8 11 3 146 197 222 +BuRd 8 11 4 209 229 240 +BuRd 8 11 5 253 219 199 +BuRd 8 11 6 244 165 130 +BuRd 8 11 7 214 96 77 +BuRd 8 11 8 178 24 43 +BuRd 9 11 1 33 102 172 +BuRd 9 11 2 67 147 195 +BuRd 9 11 3 146 197 222 +BuRd 9 11 4 209 229 240 +BuRd 9 11 5 247 247 247 +BuRd 9 11 6 253 219 199 +BuRd 9 11 7 244 165 130 +BuRd 9 11 8 214 96 77 +BuRd 9 11 9 178 24 43 +BuRd 10 11 1 5 48 97 +BuRd 10 11 2 33 102 172 +BuRd 10 11 3 67 147 195 +BuRd 10 11 4 146 197 222 +BuRd 10 11 5 209 229 240 +BuRd 10 11 6 253 219 199 +BuRd 10 11 7 244 165 130 +BuRd 10 11 8 214 96 77 +BuRd 10 11 9 178 24 43 +BuRd 10 11 10 103 0 31 +BuRd 11 11 1 5 48 97 +BuRd 11 11 2 33 102 172 +BuRd 11 11 3 67 147 195 +BuRd 11 11 4 146 197 222 +BuRd 11 11 5 209 229 240 +BuRd 11 11 6 247 247 247 +BuRd 11 11 7 253 219 199 +BuRd 11 11 8 244 165 130 +BuRd 11 11 9 214 96 77 +BuRd 11 11 10 178 24 43 +BuRd 11 11 11 103 0 31 +BuYlRd 2 11 1 145 191 219 +BuYlRd 2 11 2 252 141 89 +BuYlRd 3 11 1 145 191 219 +BuYlRd 3 11 2 255 255 191 +BuYlRd 3 11 3 252 141 89 +BuYlRd 4 11 1 44 123 182 +BuYlRd 4 11 2 171 217 233 +BuYlRd 4 11 3 253 174 97 +BuYlRd 4 11 4 215 25 28 +BuYlRd 5 11 1 44 123 182 +BuYlRd 5 11 2 171 217 233 +BuYlRd 5 11 3 255 255 191 +BuYlRd 5 11 4 253 174 97 +BuYlRd 5 11 5 215 25 28 +BuYlRd 6 11 1 69 117 180 +BuYlRd 6 11 2 145 191 219 +BuYlRd 6 11 3 224 243 248 +BuYlRd 6 11 4 254 224 144 +BuYlRd 6 11 5 252 141 89 +BuYlRd 6 11 6 215 48 39 +BuYlRd 7 11 1 69 117 180 +BuYlRd 7 11 2 145 191 219 +BuYlRd 7 11 3 224 243 248 +BuYlRd 7 11 4 255 255 191 +BuYlRd 7 11 5 254 224 144 +BuYlRd 7 11 6 252 141 89 +BuYlRd 7 11 7 215 48 39 +BuYlRd 8 11 1 69 117 180 +BuYlRd 8 11 2 116 173 209 +BuYlRd 8 11 3 171 217 233 +BuYlRd 8 11 4 224 243 248 +BuYlRd 8 11 5 254 224 144 +BuYlRd 8 11 6 253 174 97 +BuYlRd 8 11 7 244 109 67 +BuYlRd 8 11 8 215 48 39 +BuYlRd 9 11 1 69 117 180 +BuYlRd 9 11 2 116 173 209 +BuYlRd 9 11 3 171 217 233 +BuYlRd 9 11 4 224 243 248 +BuYlRd 9 11 5 255 255 191 +BuYlRd 9 11 6 254 224 144 +BuYlRd 9 11 7 253 174 97 +BuYlRd 9 11 8 244 109 67 +BuYlRd 9 11 9 215 48 39 +BuYlRd 10 11 1 49 54 149 +BuYlRd 10 11 2 69 117 180 +BuYlRd 10 11 3 116 173 209 +BuYlRd 10 11 4 171 217 233 +BuYlRd 10 11 5 224 243 248 +BuYlRd 10 11 6 254 224 144 +BuYlRd 10 11 7 253 174 97 +BuYlRd 10 11 8 244 109 67 +BuYlRd 10 11 9 215 48 39 +BuYlRd 10 11 10 165 0 38 +BuYlRd 11 11 1 49 54 149 +BuYlRd 11 11 2 69 117 180 +BuYlRd 11 11 3 116 173 209 +BuYlRd 11 11 4 171 217 233 +BuYlRd 11 11 5 224 243 248 +BuYlRd 11 11 6 255 255 191 +BuYlRd 11 11 7 254 224 144 +BuYlRd 11 11 8 253 174 97 +BuYlRd 11 11 9 244 109 67 +BuYlRd 11 11 10 215 48 39 +BuYlRd 11 11 11 165 0 38 +PRGn 2 11 1 175 141 195 +PRGn 2 11 2 127 191 123 +PRGn 3 11 1 175 141 195 +PRGn 3 11 2 247 247 247 +PRGn 3 11 3 127 191 123 +PRGn 4 11 1 123 50 148 +PRGn 4 11 2 194 165 207 +PRGn 4 11 3 166 219 160 +PRGn 4 11 4 0 136 55 +PRGn 5 11 1 123 50 148 +PRGn 5 11 2 194 165 207 +PRGn 5 11 3 247 247 247 +PRGn 5 11 4 166 219 160 +PRGn 5 11 5 0 136 55 +PRGn 6 11 1 118 42 131 +PRGn 6 11 2 175 141 195 +PRGn 6 11 3 231 212 232 +PRGn 6 11 4 217 240 211 +PRGn 6 11 5 127 191 123 +PRGn 6 11 6 27 120 55 +PRGn 7 11 1 118 42 131 +PRGn 7 11 2 175 141 195 +PRGn 7 11 3 231 212 232 +PRGn 7 11 4 247 247 247 +PRGn 7 11 5 217 240 211 +PRGn 7 11 6 127 191 123 +PRGn 7 11 7 27 120 55 +PRGn 8 11 1 118 42 131 +PRGn 8 11 2 153 112 171 +PRGn 8 11 3 194 165 207 +PRGn 8 11 4 231 212 232 +PRGn 8 11 5 217 240 211 +PRGn 8 11 6 166 219 160 +PRGn 8 11 7 90 174 97 +PRGn 8 11 8 27 120 55 +PRGn 9 11 1 118 42 131 +PRGn 9 11 2 153 112 171 +PRGn 9 11 3 194 165 207 +PRGn 9 11 4 231 212 232 +PRGn 9 11 5 247 247 247 +PRGn 9 11 6 217 240 211 +PRGn 9 11 7 166 219 160 +PRGn 9 11 8 90 174 97 +PRGn 9 11 9 27 120 55 +PRGn 10 11 1 64 0 75 +PRGn 10 11 2 118 42 131 +PRGn 10 11 3 153 112 171 +PRGn 10 11 4 194 165 207 +PRGn 10 11 5 231 212 232 +PRGn 10 11 6 217 240 211 +PRGn 10 11 7 166 219 160 +PRGn 10 11 8 90 174 97 +PRGn 10 11 9 27 120 55 +PRGn 10 11 10 0 68 27 +PRGn 11 11 1 64 0 75 +PRGn 11 11 2 118 42 131 +PRGn 11 11 3 153 112 171 +PRGn 11 11 4 194 165 207 +PRGn 11 11 5 231 212 232 +PRGn 11 11 6 247 247 247 +PRGn 11 11 7 217 240 211 +PRGn 11 11 8 166 219 160 +PRGn 11 11 9 90 174 97 +PRGn 11 11 10 27 120 55 +PRGn 11 11 11 0 68 27 +PiYG 2 11 1 233 163 201 +PiYG 2 11 2 161 215 106 +PiYG 3 11 1 233 163 201 +PiYG 3 11 2 247 247 247 +PiYG 3 11 3 161 215 106 +PiYG 4 11 1 208 28 139 +PiYG 4 11 2 241 182 218 +PiYG 4 11 3 184 225 134 +PiYG 4 11 4 77 172 38 +PiYG 5 11 1 208 28 139 +PiYG 5 11 2 241 182 218 +PiYG 5 11 3 247 247 247 +PiYG 5 11 4 184 225 134 +PiYG 5 11 5 77 172 38 +PiYG 6 11 1 197 27 125 +PiYG 6 11 2 233 163 201 +PiYG 6 11 3 253 224 239 +PiYG 6 11 4 230 245 208 +PiYG 6 11 5 161 215 106 +PiYG 6 11 6 77 146 33 +PiYG 7 11 1 197 27 125 +PiYG 7 11 2 233 163 201 +PiYG 7 11 3 253 224 239 +PiYG 7 11 4 247 247 247 +PiYG 7 11 5 230 245 208 +PiYG 7 11 6 161 215 106 +PiYG 7 11 7 77 146 33 +PiYG 8 11 1 197 27 125 +PiYG 8 11 2 222 119 174 +PiYG 8 11 3 241 182 218 +PiYG 8 11 4 253 224 239 +PiYG 8 11 5 230 245 208 +PiYG 8 11 6 184 225 134 +PiYG 8 11 7 127 188 65 +PiYG 8 11 8 77 146 33 +PiYG 9 11 1 197 27 125 +PiYG 9 11 2 222 119 174 +PiYG 9 11 3 241 182 218 +PiYG 9 11 4 253 224 239 +PiYG 9 11 5 247 247 247 +PiYG 9 11 6 230 245 208 +PiYG 9 11 7 184 225 134 +PiYG 9 11 8 127 188 65 +PiYG 9 11 9 77 146 33 +PiYG 10 11 1 142 1 82 +PiYG 10 11 2 197 27 125 +PiYG 10 11 3 222 119 174 +PiYG 10 11 4 241 182 218 +PiYG 10 11 5 253 224 239 +PiYG 10 11 6 230 245 208 +PiYG 10 11 7 184 225 134 +PiYG 10 11 8 127 188 65 +PiYG 10 11 9 77 146 33 +PiYG 10 11 10 39 100 25 +PiYG 11 11 1 142 1 82 +PiYG 11 11 2 197 27 125 +PiYG 11 11 3 222 119 174 +PiYG 11 11 4 241 182 218 +PiYG 11 11 5 253 224 239 +PiYG 11 11 6 247 247 247 +PiYG 11 11 7 230 245 208 +PiYG 11 11 8 184 225 134 +PiYG 11 11 9 127 188 65 +PiYG 11 11 10 77 146 33 +PiYG 11 11 11 39 100 25 +PuOr 2 11 1 241 163 64 +PuOr 2 11 2 153 142 195 +PuOr 3 11 1 241 163 64 +PuOr 3 11 2 247 247 247 +PuOr 3 11 3 153 142 195 +PuOr 4 11 1 230 97 1 +PuOr 4 11 2 253 184 99 +PuOr 4 11 3 178 171 210 +PuOr 4 11 4 94 60 153 +PuOr 5 11 1 230 97 1 +PuOr 5 11 2 253 184 99 +PuOr 5 11 3 247 247 247 +PuOr 5 11 4 178 171 210 +PuOr 5 11 5 94 60 153 +PuOr 6 11 1 179 88 6 +PuOr 6 11 2 241 163 64 +PuOr 6 11 3 254 224 182 +PuOr 6 11 4 216 218 235 +PuOr 6 11 5 153 142 195 +PuOr 6 11 6 84 39 136 +PuOr 7 11 1 179 88 6 +PuOr 7 11 2 241 163 64 +PuOr 7 11 3 254 224 182 +PuOr 7 11 4 247 247 247 +PuOr 7 11 5 216 218 235 +PuOr 7 11 6 153 142 195 +PuOr 7 11 7 84 39 136 +PuOr 8 11 1 179 88 6 +PuOr 8 11 2 224 130 20 +PuOr 8 11 3 253 184 99 +PuOr 8 11 4 254 224 182 +PuOr 8 11 5 216 218 235 +PuOr 8 11 6 178 171 210 +PuOr 8 11 7 128 115 172 +PuOr 8 11 8 84 39 136 +PuOr 9 11 1 179 88 6 +PuOr 9 11 2 224 130 20 +PuOr 9 11 3 253 184 99 +PuOr 9 11 4 254 224 182 +PuOr 9 11 5 247 247 247 +PuOr 9 11 6 216 218 235 +PuOr 9 11 7 178 171 210 +PuOr 9 11 8 128 115 172 +PuOr 9 11 9 84 39 136 +PuOr 10 11 1 127 59 8 +PuOr 10 11 2 179 88 6 +PuOr 10 11 3 224 130 20 +PuOr 10 11 4 253 184 99 +PuOr 10 11 5 254 224 182 +PuOr 10 11 6 216 218 235 +PuOr 10 11 7 178 171 210 +PuOr 10 11 8 128 115 172 +PuOr 10 11 9 84 39 136 +PuOr 10 11 10 45 0 75 +PuOr 11 11 1 127 59 8 +PuOr 11 11 2 179 88 6 +PuOr 11 11 3 224 130 20 +PuOr 11 11 4 253 184 99 +PuOr 11 11 5 254 224 182 +PuOr 11 11 6 247 247 247 +PuOr 11 11 7 216 218 235 +PuOr 11 11 8 178 171 210 +PuOr 11 11 9 128 115 172 +PuOr 11 11 10 84 39 136 +PuOr 11 11 11 45 0 75 +RdBu 2 11 1 239 138 98 +RdBu 2 11 2 103 169 207 +RdBu 3 11 1 239 138 98 +RdBu 3 11 2 247 247 247 +RdBu 3 11 3 103 169 207 +RdBu 4 11 1 202 0 32 +RdBu 4 11 2 244 165 130 +RdBu 4 11 3 146 197 222 +RdBu 4 11 4 5 113 176 +RdBu 5 11 1 202 0 32 +RdBu 5 11 2 244 165 130 +RdBu 5 11 3 247 247 247 +RdBu 5 11 4 146 197 222 +RdBu 5 11 5 5 113 176 +RdBu 6 11 1 178 24 43 +RdBu 6 11 2 239 138 98 +RdBu 6 11 3 253 219 199 +RdBu 6 11 4 209 229 240 +RdBu 6 11 5 103 169 207 +RdBu 6 11 6 33 102 172 +RdBu 7 11 1 178 24 43 +RdBu 7 11 2 239 138 98 +RdBu 7 11 3 253 219 199 +RdBu 7 11 4 247 247 247 +RdBu 7 11 5 209 229 240 +RdBu 7 11 6 103 169 207 +RdBu 7 11 7 33 102 172 +RdBu 8 11 1 178 24 43 +RdBu 8 11 2 214 96 77 +RdBu 8 11 3 244 165 130 +RdBu 8 11 4 253 219 199 +RdBu 8 11 5 209 229 240 +RdBu 8 11 6 146 197 222 +RdBu 8 11 7 67 147 195 +RdBu 8 11 8 33 102 172 +RdBu 9 11 1 178 24 43 +RdBu 9 11 2 214 96 77 +RdBu 9 11 3 244 165 130 +RdBu 9 11 4 253 219 199 +RdBu 9 11 5 247 247 247 +RdBu 9 11 6 209 229 240 +RdBu 9 11 7 146 197 222 +RdBu 9 11 8 67 147 195 +RdBu 9 11 9 33 102 172 +RdBu 10 11 1 103 0 31 +RdBu 10 11 2 178 24 43 +RdBu 10 11 3 214 96 77 +RdBu 10 11 4 244 165 130 +RdBu 10 11 5 253 219 199 +RdBu 10 11 6 209 229 240 +RdBu 10 11 7 146 197 222 +RdBu 10 11 8 67 147 195 +RdBu 10 11 9 33 102 172 +RdBu 10 11 10 5 48 97 +RdBu 11 11 1 103 0 31 +RdBu 11 11 2 178 24 43 +RdBu 11 11 3 214 96 77 +RdBu 11 11 4 244 165 130 +RdBu 11 11 5 253 219 199 +RdBu 11 11 6 247 247 247 +RdBu 11 11 7 209 229 240 +RdBu 11 11 8 146 197 222 +RdBu 11 11 9 67 147 195 +RdBu 11 11 10 33 102 172 +RdBu 11 11 11 5 48 97 +RdGy 2 11 1 239 138 98 +RdGy 2 11 2 153 153 153 +RdGy 3 11 1 239 138 98 +RdGy 3 11 2 255 255 255 +RdGy 3 11 3 153 153 153 +RdGy 4 11 1 202 0 32 +RdGy 4 11 2 244 165 130 +RdGy 4 11 3 186 186 186 +RdGy 4 11 4 64 64 64 +RdGy 5 11 1 202 0 32 +RdGy 5 11 2 244 165 130 +RdGy 5 11 3 255 255 255 +RdGy 5 11 4 186 186 186 +RdGy 5 11 5 64 64 64 +RdGy 6 11 1 178 24 43 +RdGy 6 11 2 239 138 98 +RdGy 6 11 3 253 219 199 +RdGy 6 11 4 224 224 224 +RdGy 6 11 5 153 153 153 +RdGy 6 11 6 77 77 77 +RdGy 7 11 1 178 24 43 +RdGy 7 11 2 239 138 98 +RdGy 7 11 3 253 219 199 +RdGy 7 11 4 255 255 255 +RdGy 7 11 5 224 224 224 +RdGy 7 11 6 153 153 153 +RdGy 7 11 7 77 77 77 +RdGy 8 11 1 178 24 43 +RdGy 8 11 2 214 96 77 +RdGy 8 11 3 244 165 130 +RdGy 8 11 4 253 219 199 +RdGy 8 11 5 224 224 224 +RdGy 8 11 6 186 186 186 +RdGy 8 11 7 135 135 135 +RdGy 8 11 8 77 77 77 +RdGy 9 11 1 178 24 43 +RdGy 9 11 2 214 96 77 +RdGy 9 11 3 244 165 130 +RdGy 9 11 4 253 219 199 +RdGy 9 11 5 255 255 255 +RdGy 9 11 6 224 224 224 +RdGy 9 11 7 186 186 186 +RdGy 9 11 8 135 135 135 +RdGy 9 11 9 77 77 77 +RdGy 10 11 1 103 0 31 +RdGy 10 11 2 178 24 43 +RdGy 10 11 3 214 96 77 +RdGy 10 11 4 244 165 130 +RdGy 10 11 5 253 219 199 +RdGy 10 11 6 224 224 224 +RdGy 10 11 7 186 186 186 +RdGy 10 11 8 135 135 135 +RdGy 10 11 9 77 77 77 +RdGy 10 11 10 26 26 26 +RdGy 11 11 1 103 0 31 +RdGy 11 11 2 178 24 43 +RdGy 11 11 3 214 96 77 +RdGy 11 11 4 244 165 130 +RdGy 11 11 5 253 219 199 +RdGy 11 11 6 255 255 255 +RdGy 11 11 7 224 224 224 +RdGy 11 11 8 186 186 186 +RdGy 11 11 9 135 135 135 +RdGy 11 11 10 77 77 77 +RdGy 11 11 11 26 26 26 +RdYlBu 2 11 1 252 141 89 +RdYlBu 2 11 2 145 191 219 +RdYlBu 3 11 1 252 141 89 +RdYlBu 3 11 2 255 255 191 +RdYlBu 3 11 3 145 191 219 +RdYlBu 4 11 1 215 25 28 +RdYlBu 4 11 2 253 174 97 +RdYlBu 4 11 3 171 217 233 +RdYlBu 4 11 4 44 123 182 +RdYlBu 5 11 1 215 25 28 +RdYlBu 5 11 2 253 174 97 +RdYlBu 5 11 3 255 255 191 +RdYlBu 5 11 4 171 217 233 +RdYlBu 5 11 5 44 123 182 +RdYlBu 6 11 1 215 48 39 +RdYlBu 6 11 2 252 141 89 +RdYlBu 6 11 3 254 224 144 +RdYlBu 6 11 4 224 243 248 +RdYlBu 6 11 5 145 191 219 +RdYlBu 6 11 6 69 117 180 +RdYlBu 7 11 1 215 48 39 +RdYlBu 7 11 2 252 141 89 +RdYlBu 7 11 3 254 224 144 +RdYlBu 7 11 4 255 255 191 +RdYlBu 7 11 5 224 243 248 +RdYlBu 7 11 6 145 191 219 +RdYlBu 7 11 7 69 117 180 +RdYlBu 8 11 1 215 48 39 +RdYlBu 8 11 2 244 109 67 +RdYlBu 8 11 3 253 174 97 +RdYlBu 8 11 4 254 224 144 +RdYlBu 8 11 5 224 243 248 +RdYlBu 8 11 6 171 217 233 +RdYlBu 8 11 7 116 173 209 +RdYlBu 8 11 8 69 117 180 +RdYlBu 9 11 1 215 48 39 +RdYlBu 9 11 2 244 109 67 +RdYlBu 9 11 3 253 174 97 +RdYlBu 9 11 4 254 224 144 +RdYlBu 9 11 5 255 255 191 +RdYlBu 9 11 6 224 243 248 +RdYlBu 9 11 7 171 217 233 +RdYlBu 9 11 8 116 173 209 +RdYlBu 9 11 9 69 117 180 +RdYlBu 10 11 1 165 0 38 +RdYlBu 10 11 2 215 48 39 +RdYlBu 10 11 3 244 109 67 +RdYlBu 10 11 4 253 174 97 +RdYlBu 10 11 5 254 224 144 +RdYlBu 10 11 6 224 243 248 +RdYlBu 10 11 7 171 217 233 +RdYlBu 10 11 8 116 173 209 +RdYlBu 10 11 9 69 117 180 +RdYlBu 10 11 10 49 54 149 +RdYlBu 11 11 1 165 0 38 +RdYlBu 11 11 2 215 48 39 +RdYlBu 11 11 3 244 109 67 +RdYlBu 11 11 4 253 174 97 +RdYlBu 11 11 5 254 224 144 +RdYlBu 11 11 6 255 255 191 +RdYlBu 11 11 7 224 243 248 +RdYlBu 11 11 8 171 217 233 +RdYlBu 11 11 9 116 173 209 +RdYlBu 11 11 10 69 117 180 +RdYlBu 11 11 11 49 54 149 +RdYlGn 2 11 1 252 141 89 +RdYlGn 2 11 2 145 207 96 +RdYlGn 3 11 1 252 141 89 +RdYlGn 3 11 2 255 255 191 +RdYlGn 3 11 3 145 207 96 +RdYlGn 4 11 1 215 25 28 +RdYlGn 4 11 2 253 174 97 +RdYlGn 4 11 3 166 217 106 +RdYlGn 4 11 4 26 150 65 +RdYlGn 5 11 1 215 25 28 +RdYlGn 5 11 2 253 174 97 +RdYlGn 5 11 3 255 255 191 +RdYlGn 5 11 4 166 217 106 +RdYlGn 5 11 5 26 150 65 +RdYlGn 6 11 1 215 48 39 +RdYlGn 6 11 2 252 141 89 +RdYlGn 6 11 3 254 224 139 +RdYlGn 6 11 4 217 239 139 +RdYlGn 6 11 5 145 207 96 +RdYlGn 6 11 6 26 152 80 +RdYlGn 7 11 1 215 48 39 +RdYlGn 7 11 2 252 141 89 +RdYlGn 7 11 3 254 224 139 +RdYlGn 7 11 4 255 255 191 +RdYlGn 7 11 5 217 239 139 +RdYlGn 7 11 6 145 207 96 +RdYlGn 7 11 7 26 152 80 +RdYlGn 8 11 1 215 48 39 +RdYlGn 8 11 2 244 109 67 +RdYlGn 8 11 3 253 174 97 +RdYlGn 8 11 4 254 224 139 +RdYlGn 8 11 5 217 239 139 +RdYlGn 8 11 6 166 217 106 +RdYlGn 8 11 7 102 189 99 +RdYlGn 8 11 8 26 152 80 +RdYlGn 9 11 1 215 48 39 +RdYlGn 9 11 2 244 109 67 +RdYlGn 9 11 3 253 174 97 +RdYlGn 9 11 4 254 224 139 +RdYlGn 9 11 5 255 255 191 +RdYlGn 9 11 6 217 239 139 +RdYlGn 9 11 7 166 217 106 +RdYlGn 9 11 8 102 189 99 +RdYlGn 9 11 9 26 152 80 +RdYlGn 10 11 1 165 0 38 +RdYlGn 10 11 2 215 48 39 +RdYlGn 10 11 3 244 109 67 +RdYlGn 10 11 4 253 174 97 +RdYlGn 10 11 5 254 224 139 +RdYlGn 10 11 6 217 239 139 +RdYlGn 10 11 7 166 217 106 +RdYlGn 10 11 8 102 189 99 +RdYlGn 10 11 9 26 152 80 +RdYlGn 10 11 10 0 104 55 +RdYlGn 11 11 1 165 0 38 +RdYlGn 11 11 2 215 48 39 +RdYlGn 11 11 3 244 109 67 +RdYlGn 11 11 4 253 174 97 +RdYlGn 11 11 5 254 224 139 +RdYlGn 11 11 6 255 255 191 +RdYlGn 11 11 7 217 239 139 +RdYlGn 11 11 8 166 217 106 +RdYlGn 11 11 9 102 189 99 +RdYlGn 11 11 10 26 152 80 +RdYlGn 11 11 11 0 104 55 +Spectral 2 11 1 252 141 89 +Spectral 2 11 2 153 213 148 +Spectral 3 11 1 252 141 89 +Spectral 3 11 2 255 255 191 +Spectral 3 11 3 153 213 148 +Spectral 4 11 1 215 25 28 +Spectral 4 11 2 253 174 97 +Spectral 4 11 3 171 221 164 +Spectral 4 11 4 43 131 186 +Spectral 5 11 1 215 25 28 +Spectral 5 11 2 253 174 97 +Spectral 5 11 3 255 255 191 +Spectral 5 11 4 171 221 164 +Spectral 5 11 5 43 131 186 +Spectral 6 11 1 213 62 79 +Spectral 6 11 2 252 141 89 +Spectral 6 11 3 254 224 139 +Spectral 6 11 4 230 245 152 +Spectral 6 11 5 153 213 148 +Spectral 6 11 6 50 136 189 +Spectral 7 11 1 213 62 79 +Spectral 7 11 2 252 141 89 +Spectral 7 11 3 254 224 139 +Spectral 7 11 4 255 255 191 +Spectral 7 11 5 230 245 152 +Spectral 7 11 6 153 213 148 +Spectral 7 11 7 50 136 189 +Spectral 8 11 1 213 62 79 +Spectral 8 11 2 244 109 67 +Spectral 8 11 3 253 174 97 +Spectral 8 11 4 254 224 139 +Spectral 8 11 5 230 245 152 +Spectral 8 11 6 171 221 164 +Spectral 8 11 7 102 194 165 +Spectral 8 11 8 50 136 189 +Spectral 9 11 1 213 62 79 +Spectral 9 11 2 244 109 67 +Spectral 9 11 3 253 174 97 +Spectral 9 11 4 254 224 139 +Spectral 9 11 5 255 255 191 +Spectral 9 11 6 230 245 152 +Spectral 9 11 7 171 221 164 +Spectral 9 11 8 102 194 165 +Spectral 9 11 9 50 136 189 +Spectral 10 11 1 158 1 66 +Spectral 10 11 2 213 62 79 +Spectral 10 11 3 244 109 67 +Spectral 10 11 4 253 174 97 +Spectral 10 11 5 254 224 139 +Spectral 10 11 6 230 245 152 +Spectral 10 11 7 171 221 164 +Spectral 10 11 8 102 194 165 +Spectral 10 11 9 50 136 189 +Spectral 10 11 10 94 79 162 +Spectral 11 11 1 158 1 66 +Spectral 11 11 2 213 62 79 +Spectral 11 11 3 244 109 67 +Spectral 11 11 4 253 174 97 +Spectral 11 11 5 254 224 139 +Spectral 11 11 6 255 255 191 +Spectral 11 11 7 230 245 152 +Spectral 11 11 8 171 221 164 +Spectral 11 11 9 102 194 165 +Spectral 11 11 10 50 136 189 +Spectral 11 11 11 94 79 162 +Accent 2 8 1 127 201 127 +Accent 2 8 2 190 174 212 +Accent 3 8 1 127 201 127 +Accent 3 8 2 190 174 212 +Accent 3 8 3 253 192 134 +Accent 4 8 1 127 201 127 +Accent 4 8 2 190 174 212 +Accent 4 8 3 253 192 134 +Accent 4 8 4 255 255 153 +Accent 5 8 1 127 201 127 +Accent 5 8 2 190 174 212 +Accent 5 8 3 253 192 134 +Accent 5 8 4 255 255 153 +Accent 5 8 5 56 108 176 +Accent 6 8 1 127 201 127 +Accent 6 8 2 190 174 212 +Accent 6 8 3 253 192 134 +Accent 6 8 4 255 255 153 +Accent 6 8 5 56 108 176 +Accent 6 8 6 240 2 127 +Accent 7 8 1 127 201 127 +Accent 7 8 2 190 174 212 +Accent 7 8 3 253 192 134 +Accent 7 8 4 255 255 153 +Accent 7 8 5 56 108 176 +Accent 7 8 6 240 2 127 +Accent 7 8 7 191 91 23 +Accent 8 8 1 127 201 127 +Accent 8 8 2 190 174 212 +Accent 8 8 3 253 192 134 +Accent 8 8 4 255 255 153 +Accent 8 8 5 56 108 176 +Accent 8 8 6 240 2 127 +Accent 8 8 7 191 91 23 +Accent 8 8 8 102 102 102 +Dark2 2 8 1 27 158 119 +Dark2 2 8 2 217 95 2 +Dark2 3 8 1 27 158 119 +Dark2 3 8 2 217 95 2 +Dark2 3 8 3 117 112 179 +Dark2 4 8 1 27 158 119 +Dark2 4 8 2 217 95 2 +Dark2 4 8 3 117 112 179 +Dark2 4 8 4 231 41 138 +Dark2 5 8 1 27 158 119 +Dark2 5 8 2 217 95 2 +Dark2 5 8 3 117 112 179 +Dark2 5 8 4 231 41 138 +Dark2 5 8 5 102 166 30 +Dark2 6 8 1 27 158 119 +Dark2 6 8 2 217 95 2 +Dark2 6 8 3 117 112 179 +Dark2 6 8 4 231 41 138 +Dark2 6 8 5 102 166 30 +Dark2 6 8 6 230 171 2 +Dark2 7 8 1 27 158 119 +Dark2 7 8 2 217 95 2 +Dark2 7 8 3 117 112 179 +Dark2 7 8 4 231 41 138 +Dark2 7 8 5 102 166 30 +Dark2 7 8 6 230 171 2 +Dark2 7 8 7 166 118 29 +Dark2 8 8 1 27 158 119 +Dark2 8 8 2 217 95 2 +Dark2 8 8 3 117 112 179 +Dark2 8 8 4 231 41 138 +Dark2 8 8 5 102 166 30 +Dark2 8 8 6 230 171 2 +Dark2 8 8 7 166 118 29 +Dark2 8 8 8 102 102 102 +Paired 2 12 1 166 206 227 +Paired 2 12 2 31 120 180 +Paired 3 12 1 166 206 227 +Paired 3 12 2 31 120 180 +Paired 3 12 3 178 223 138 +Paired 4 12 1 166 206 227 +Paired 4 12 2 31 120 180 +Paired 4 12 3 178 223 138 +Paired 4 12 4 51 160 44 +Paired 5 12 1 166 206 227 +Paired 5 12 2 31 120 180 +Paired 5 12 3 178 223 138 +Paired 5 12 4 51 160 44 +Paired 5 12 5 251 154 153 +Paired 6 12 1 166 206 227 +Paired 6 12 2 31 120 180 +Paired 6 12 3 178 223 138 +Paired 6 12 4 51 160 44 +Paired 6 12 5 251 154 153 +Paired 6 12 6 227 26 28 +Paired 7 12 1 166 206 227 +Paired 7 12 2 31 120 180 +Paired 7 12 3 178 223 138 +Paired 7 12 4 51 160 44 +Paired 7 12 5 251 154 153 +Paired 7 12 6 227 26 28 +Paired 7 12 7 253 191 111 +Paired 8 12 1 166 206 227 +Paired 8 12 2 31 120 180 +Paired 8 12 3 178 223 138 +Paired 8 12 4 51 160 44 +Paired 8 12 5 251 154 153 +Paired 8 12 6 227 26 28 +Paired 8 12 7 253 191 111 +Paired 8 12 8 255 127 0 +Paired 9 12 1 166 206 227 +Paired 9 12 2 31 120 180 +Paired 9 12 3 178 223 138 +Paired 9 12 4 51 160 44 +Paired 9 12 5 251 154 153 +Paired 9 12 6 227 26 28 +Paired 9 12 7 253 191 111 +Paired 9 12 8 255 127 0 +Paired 9 12 9 202 178 214 +Paired 10 12 1 166 206 227 +Paired 10 12 2 31 120 180 +Paired 10 12 3 178 223 138 +Paired 10 12 4 51 160 44 +Paired 10 12 5 251 154 153 +Paired 10 12 6 227 26 28 +Paired 10 12 7 253 191 111 +Paired 10 12 8 255 127 0 +Paired 10 12 9 202 178 214 +Paired 10 12 10 106 61 154 +Paired 11 12 1 166 206 227 +Paired 11 12 2 31 120 180 +Paired 11 12 3 178 223 138 +Paired 11 12 4 51 160 44 +Paired 11 12 5 251 154 153 +Paired 11 12 6 227 26 28 +Paired 11 12 7 253 191 111 +Paired 11 12 8 255 127 0 +Paired 11 12 9 202 178 214 +Paired 11 12 10 106 61 154 +Paired 11 12 11 255 255 153 +Paired 12 12 1 166 206 227 +Paired 12 12 2 31 120 180 +Paired 12 12 3 178 223 138 +Paired 12 12 4 51 160 44 +Paired 12 12 5 251 154 153 +Paired 12 12 6 227 26 28 +Paired 12 12 7 253 191 111 +Paired 12 12 8 255 127 0 +Paired 12 12 9 202 178 214 +Paired 12 12 10 106 61 154 +Paired 12 12 11 255 255 153 +Paired 12 12 12 177 89 40 +Pastel1 2 9 1 251 180 174 +Pastel1 2 9 2 179 205 227 +Pastel1 3 9 1 251 180 174 +Pastel1 3 9 2 179 205 227 +Pastel1 3 9 3 204 235 197 +Pastel1 4 9 1 251 180 174 +Pastel1 4 9 2 179 205 227 +Pastel1 4 9 3 204 235 197 +Pastel1 4 9 4 222 203 228 +Pastel1 5 9 1 251 180 174 +Pastel1 5 9 2 179 205 227 +Pastel1 5 9 3 204 235 197 +Pastel1 5 9 4 222 203 228 +Pastel1 5 9 5 254 217 166 +Pastel1 6 9 1 251 180 174 +Pastel1 6 9 2 179 205 227 +Pastel1 6 9 3 204 235 197 +Pastel1 6 9 4 222 203 228 +Pastel1 6 9 5 254 217 166 +Pastel1 6 9 6 255 255 204 +Pastel1 7 9 1 251 180 174 +Pastel1 7 9 2 179 205 227 +Pastel1 7 9 3 204 235 197 +Pastel1 7 9 4 222 203 228 +Pastel1 7 9 5 254 217 166 +Pastel1 7 9 6 255 255 204 +Pastel1 7 9 7 229 216 189 +Pastel1 8 9 1 251 180 174 +Pastel1 8 9 2 179 205 227 +Pastel1 8 9 3 204 235 197 +Pastel1 8 9 4 222 203 228 +Pastel1 8 9 5 254 217 166 +Pastel1 8 9 6 255 255 204 +Pastel1 8 9 7 229 216 189 +Pastel1 8 9 8 253 218 236 +Pastel1 9 9 1 251 180 174 +Pastel1 9 9 2 179 205 227 +Pastel1 9 9 3 204 235 197 +Pastel1 9 9 4 222 203 228 +Pastel1 9 9 5 254 217 166 +Pastel1 9 9 6 255 255 204 +Pastel1 9 9 7 229 216 189 +Pastel1 9 9 8 253 218 236 +Pastel1 9 9 9 242 242 242 +Pastel2 2 8 1 179 226 205 +Pastel2 2 8 2 253 205 172 +Pastel2 3 8 1 179 226 205 +Pastel2 3 8 2 253 205 172 +Pastel2 3 8 3 203 213 232 +Pastel2 4 8 1 179 226 205 +Pastel2 4 8 2 253 205 172 +Pastel2 4 8 3 203 213 232 +Pastel2 4 8 4 244 202 228 +Pastel2 5 8 1 179 226 205 +Pastel2 5 8 2 253 205 172 +Pastel2 5 8 3 203 213 232 +Pastel2 5 8 4 244 202 228 +Pastel2 5 8 5 230 245 201 +Pastel2 6 8 1 179 226 205 +Pastel2 6 8 2 253 205 172 +Pastel2 6 8 3 203 213 232 +Pastel2 6 8 4 244 202 228 +Pastel2 6 8 5 230 245 201 +Pastel2 6 8 6 255 242 174 +Pastel2 7 8 1 179 226 205 +Pastel2 7 8 2 253 205 172 +Pastel2 7 8 3 203 213 232 +Pastel2 7 8 4 244 202 228 +Pastel2 7 8 5 230 245 201 +Pastel2 7 8 6 255 242 174 +Pastel2 7 8 7 241 226 204 +Pastel2 8 8 1 179 226 205 +Pastel2 8 8 2 253 205 172 +Pastel2 8 8 3 203 213 232 +Pastel2 8 8 4 244 202 228 +Pastel2 8 8 5 230 245 201 +Pastel2 8 8 6 255 242 174 +Pastel2 8 8 7 241 226 204 +Pastel2 8 8 8 204 204 204 +Set1 2 9 1 228 26 28 +Set1 2 9 2 55 126 184 +Set1 3 9 1 228 26 28 +Set1 3 9 2 55 126 184 +Set1 3 9 3 77 175 74 +Set1 4 9 1 228 26 28 +Set1 4 9 2 55 126 184 +Set1 4 9 3 77 175 74 +Set1 4 9 4 152 78 163 +Set1 5 9 1 228 26 28 +Set1 5 9 2 55 126 184 +Set1 5 9 3 77 175 74 +Set1 5 9 4 152 78 163 +Set1 5 9 5 255 127 0 +Set1 6 9 1 228 26 28 +Set1 6 9 2 55 126 184 +Set1 6 9 3 77 175 74 +Set1 6 9 4 152 78 163 +Set1 6 9 5 255 127 0 +Set1 6 9 6 255 255 51 +Set1 7 9 1 228 26 28 +Set1 7 9 2 55 126 184 +Set1 7 9 3 77 175 74 +Set1 7 9 4 152 78 163 +Set1 7 9 5 255 127 0 +Set1 7 9 6 255 255 51 +Set1 7 9 7 166 86 40 +Set1 8 9 1 228 26 28 +Set1 8 9 2 55 126 184 +Set1 8 9 3 77 175 74 +Set1 8 9 4 152 78 163 +Set1 8 9 5 255 127 0 +Set1 8 9 6 255 255 51 +Set1 8 9 7 166 86 40 +Set1 8 9 8 247 129 191 +Set1 9 9 1 228 26 28 +Set1 9 9 2 55 126 184 +Set1 9 9 3 77 175 74 +Set1 9 9 4 152 78 163 +Set1 9 9 5 255 127 0 +Set1 9 9 6 255 255 51 +Set1 9 9 7 166 86 40 +Set1 9 9 8 247 129 191 +Set1 9 9 9 153 153 153 +Set2 2 8 1 102 194 165 +Set2 2 8 2 252 141 98 +Set2 3 8 1 102 194 165 +Set2 3 8 2 252 141 98 +Set2 3 8 3 141 160 203 +Set2 4 8 1 102 194 165 +Set2 4 8 2 252 141 98 +Set2 4 8 3 141 160 203 +Set2 4 8 4 231 138 195 +Set2 5 8 1 102 194 165 +Set2 5 8 2 252 141 98 +Set2 5 8 3 141 160 203 +Set2 5 8 4 231 138 195 +Set2 5 8 5 166 216 84 +Set2 6 8 1 102 194 165 +Set2 6 8 2 252 141 98 +Set2 6 8 3 141 160 203 +Set2 6 8 4 231 138 195 +Set2 6 8 5 166 216 84 +Set2 6 8 6 255 217 47 +Set2 7 8 1 102 194 165 +Set2 7 8 2 252 141 98 +Set2 7 8 3 141 160 203 +Set2 7 8 4 231 138 195 +Set2 7 8 5 166 216 84 +Set2 7 8 6 255 217 47 +Set2 7 8 7 229 196 148 +Set2 8 8 1 102 194 165 +Set2 8 8 2 252 141 98 +Set2 8 8 3 141 160 203 +Set2 8 8 4 231 138 195 +Set2 8 8 5 166 216 84 +Set2 8 8 6 255 217 47 +Set2 8 8 7 229 196 148 +Set2 8 8 8 179 179 179 +Set3 2 12 1 141 211 199 +Set3 2 12 2 255 255 179 +Set3 3 12 1 141 211 199 +Set3 3 12 2 255 255 179 +Set3 3 12 3 190 186 218 +Set3 4 12 1 141 211 199 +Set3 4 12 2 255 255 179 +Set3 4 12 3 190 186 218 +Set3 4 12 4 251 128 114 +Set3 5 12 1 141 211 199 +Set3 5 12 2 255 255 179 +Set3 5 12 3 190 186 218 +Set3 5 12 4 251 128 114 +Set3 5 12 5 128 177 211 +Set3 6 12 1 141 211 199 +Set3 6 12 2 255 255 179 +Set3 6 12 3 190 186 218 +Set3 6 12 4 251 128 114 +Set3 6 12 5 128 177 211 +Set3 6 12 6 253 180 98 +Set3 7 12 1 141 211 199 +Set3 7 12 2 255 255 179 +Set3 7 12 3 190 186 218 +Set3 7 12 4 251 128 114 +Set3 7 12 5 128 177 211 +Set3 7 12 6 253 180 98 +Set3 7 12 7 179 222 105 +Set3 8 12 1 141 211 199 +Set3 8 12 2 255 255 179 +Set3 8 12 3 190 186 218 +Set3 8 12 4 251 128 114 +Set3 8 12 5 128 177 211 +Set3 8 12 6 253 180 98 +Set3 8 12 7 179 222 105 +Set3 8 12 8 252 205 229 +Set3 9 12 1 141 211 199 +Set3 9 12 2 255 255 179 +Set3 9 12 3 190 186 218 +Set3 9 12 4 251 128 114 +Set3 9 12 5 128 177 211 +Set3 9 12 6 253 180 98 +Set3 9 12 7 179 222 105 +Set3 9 12 8 252 205 229 +Set3 9 12 9 217 217 217 +Set3 10 12 1 141 211 199 +Set3 10 12 2 255 255 179 +Set3 10 12 3 190 186 218 +Set3 10 12 4 251 128 114 +Set3 10 12 5 128 177 211 +Set3 10 12 6 253 180 98 +Set3 10 12 7 179 222 105 +Set3 10 12 8 252 205 229 +Set3 10 12 9 217 217 217 +Set3 10 12 10 188 128 189 +Set3 11 12 1 141 211 199 +Set3 11 12 2 255 255 179 +Set3 11 12 3 190 186 218 +Set3 11 12 4 251 128 114 +Set3 11 12 5 128 177 211 +Set3 11 12 6 253 180 98 +Set3 11 12 7 179 222 105 +Set3 11 12 8 252 205 229 +Set3 11 12 9 217 217 217 +Set3 11 12 10 188 128 189 +Set3 11 12 11 204 235 197 +Set3 12 12 1 141 211 199 +Set3 12 12 2 255 255 179 +Set3 12 12 3 190 186 218 +Set3 12 12 4 251 128 114 +Set3 12 12 5 128 177 211 +Set3 12 12 6 253 180 98 +Set3 12 12 7 179 222 105 +Set3 12 12 8 252 205 229 +Set3 12 12 9 217 217 217 +Set3 12 12 10 188 128 189 +Set3 12 12 11 204 235 197 +Set3 12 12 12 255 237 111 diff --git a/notebooks/msna/Codes/ado/s/spmap_diagram.ado b/notebooks/msna/Codes/ado/s/spmap_diagram.ado new file mode 100644 index 00000000..d002d6b3 --- /dev/null +++ b/notebooks/msna/Codes/ado/s/spmap_diagram.ado @@ -0,0 +1,1147 @@ +*! -spmap_diagram-: Auxiliary program for -spmap- +*! Version 1.3.3 - 09 January 2018 - StataCorp edit for stroke align +*! Version 1.3.2 - 19 June 2017 - StataCorp edit to plot line in diagram +*! Version 1.3.1 - 29 March 2017 - StataCorp edit to tempfile macros +*! Version 1.3.0 - 13 March 2017 +*! Version 1.2.0 - 14 March 2008 +*! Version 1.1.0 - 7 May 2007 +*! Version 1.0.0 - 7 December 2006 +*! Author: Maurizio Pisati +*! Department of Sociology and Social Research +*! University of Milano Bicocca (Italy) +*! maurizio.pisati@unimib.it + + + + +* ---------------------------------------------------------------------------- +* 1. Define program +* ---------------------------------------------------------------------------- + +program spmap_diagram, rclass +version 9.2 + + + + +* ---------------------------------------------------------------------------- +* 2. Define syntax +* ---------------------------------------------------------------------------- + +syntax, [Data(string)] /// + [Select(string asis)] /// + [BY(string)] /// + /// + [Xcoord(string)] /// + [Ycoord(string)] /// + [Variables(string)] /// + [Type(string)] /// + /// + [PROPortional(string)] /// + [PRange(string)] /// + /// + [Range(string)] /// + [REFVal(string)] /// + [REFWeight(string)] /// + [REFColor(string asis)] /// + [REFSize(string)] /// + /// + [SIze(string)] /// + [FColor(string asis)] /// + [OColor(string asis)] /// + [OSize(string)] /// + [OAlign(string asis)] /// + /// + [LEGENDA(string)] /// + [LEGTitle(string asis)] /// + [LEGShow(string)] /// + [LEGCount] + + + + +* ---------------------------------------------------------------------------- +* 3. Check syntax +* ---------------------------------------------------------------------------- + +/* Preserve data */ +preserve + +/* Check and open dataset */ +if ("`data'" != "") { + if (substr(reverse("`data'"),1,4) != "atd.") { + local data "`data'.dta" + } + capture confirm file "`data'" + if _rc { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: file " /// + "{bf:`data'} specified in suboption {bf:{ul:d}ata()} " /// + "not found{p_end}" + exit 601 + } + use "`data'", clear +} + +/* Select relevant records */ +if (`"`select'"' != "") { + cap `select' + if _rc { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: suboption " /// + "{bf:{ul:s}elect()} specified incorrectly{p_end}" + exit 198 + } +} + +/* Check option by() */ +if ("`by'" != "") { + cap unab by : `by' + if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "variable {bf:`by'} specified in suboption " /// + "{bf:{ul:by}()} not found{p_end}" + exit 111 + } + if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "string {bf:`by'} specified in suboption " /// + "{bf:{ul:by}()} is not a valid variable " /// + "name{p_end}" + exit 198 + } + local NW : word count `by' + if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:by}()} accepts only one " /// + "variable{p_end}" + exit 198 + } +} + +/* Check option xcoord() */ +if ("`xcoord'" == "") { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: suboption " /// + "{bf:{ul:x}coord()} is required{p_end}" + exit 198 +} +cap unab xcoord : `xcoord' +if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "variable {bf:`xcoord'} specified in suboption " /// + "{bf:{ul:x}coord()} not found{p_end}" + exit 111 +} +if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "string {bf:`xcoord'} specified in suboption " /// + "{bf:{ul:x}coord()} is not a valid variable " /// + "name{p_end}" + exit 198 +} +local NW : word count `xcoord' +if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:x}coord()} accepts only one " /// + "variable{p_end}" + exit 198 +} +cap confirm numeric variable `xcoord', exact +if _rc { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:x}coord()} accepts only " /// + "numeric variables{p_end}" + exit 7 +} + +/* Check option ycoord() */ +if ("`ycoord'" == "") { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: suboption " /// + "{bf:{ul:y}coord()} is required{p_end}" + exit 198 +} +cap unab ycoord : `ycoord' +if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "variable {bf:`ycoord'} specified in suboption " /// + "{bf:{ul:y}coord()} not found{p_end}" + exit 111 +} +if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "string {bf:`ycoord'} specified in suboption " /// + "{bf:{ul:y}coord()} is not a valid variable " /// + "name{p_end}" + exit 198 +} +local NW : word count `ycoord' +if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:y}coord()} accepts only one " /// + "variable{p_end}" + exit 198 +} +cap confirm numeric variable `ycoord', exact +if _rc { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:y}coord()} accepts only " /// + "numeric variables{p_end}" + exit 7 +} + +/* Check option variables() */ +if ("`variables'" == "") { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: suboption " /// + "{bf:{ul:v}ariables()} is required{p_end}" + exit 198 +} +cap unab variables : `variables' +if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "variable(s) {bf:`variables'} specified in suboption " /// + "{bf:{ul:v}ariables()} not found{p_end}" + exit 111 +} +if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "string {bf:`variables'} specified in suboption " /// + "{bf:{ul:v}ariables()} does not contain valid " /// + "variable names{p_end}" + exit 198 +} +local NVAR : word count `variables' +cap confirm numeric variable `variables', exact +if _rc { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:v}ariables()} accepts only " /// + "numeric variables{p_end}" + exit 7 +} + +/* Check option type() */ +if (`NVAR' > 1) local type "pie" +else { + if ("`type'" != "") { + local LIST "frect pie" + local EXIST : list posof "`type'" in LIST + if !`EXIST' { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:t}ype()} accepts only one " /// + "of the following keywords: {bf:`LIST'}{p_end}" + exit 198 + } + } + else { + local type "frect" + } +} + +/* Check option proportional() */ +if ("`proportional'" != "") { + cap unab proportional : `proportional' + if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "variable {bf:`proportional'} specified in " /// + "suboption {bf:{ul:prop}ortional()} not " /// + "found{p_end}" + exit 111 + } + if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "string {bf:`proportional'} specified in " /// + "suboption {bf:{ul:prop}ortional()} is not " /// + "a valid variable name{p_end}" + exit 198 + } + local NW : word count `proportional' + if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:prop}ortional()} accepts " /// + "only one variable{p_end}" + exit 198 + } + cap confirm numeric variable `proportional', exact + if _rc { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:prop}ortional()} accepts " /// + "only numeric variables{p_end}" + exit 7 + } +} + +/* Check option prange() */ +if ("`prange'" != "") & ("`proportional'" != "") { + local NW : word count `prange' + if (`NW' != 2) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:pr}ange()} requires exactly " /// + "2 arguments{p_end}" + exit 198 + } + foreach W in `prange' { + cap confirm number `W' + if _rc { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:pr}ange()} accepts only " /// + "numbers{p_end}" + exit 7 + } + } + local N1 : word 1 of `prange' + local N2 : word 2 of `prange' + if (`N1' == `N2') { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "the two numbers specified in suboption " /// + "{bf:{ul:pr}ange()} must be different{p_end}" + exit 198 + } + local MIN = min(`N1', `N2') + local MAX = max(`N1', `N2') + local prange "`MIN' `MAX'" +} + +/* Check option range() */ +if ("`range'" != "") & ("`type'" == "frect") { + local NW : word count `range' + if (`NW' != 2) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:r}ange()} requires exactly " /// + "2 arguments{p_end}" + exit 198 + } + foreach W in `range' { + cap confirm number `W' + if _rc { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:r}ange()} accepts only " /// + "numbers{p_end}" + exit 7 + } + } + local N1 : word 1 of `range' + local N2 : word 2 of `range' + if (`N1' == `N2') { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "the two numbers specified in suboption " /// + "{bf:{ul:r}ange()} must be different{p_end}" + exit 198 + } + local MIN = min(`N1', `N2') + local MAX = max(`N1', `N2') + local range "`MIN' `MAX'" +} + +/* Check option refval() */ +if ("`refval'" != "") & ("`type'" == "frect") { + cap confirm number `refval' + if _rc { + local LIST "mean median" + local EXIST : list posof "`refval'" in LIST + if !`EXIST' { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:refv}al()} accepts only " /// + "numbers or one of the following keywords: " /// + "{bf:`LIST'}{p_end}" + exit 198 + } + } + else local RVTYPE "NUM" +} + +/* Check option refweight() */ +if ("`refweight'" != "") & ("`type'" == "frect") { + cap unab refweight : `refweight' + if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "variable {bf:`refweight'} specified in " /// + "suboption {bf:{ul:refw}eight()} not " /// + "found{p_end}" + exit 111 + } + if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "string {bf:`refweight'} specified in " /// + "suboption {bf:{ul:refw}eight()} is not " /// + "a valid variable name{p_end}" + exit 198 + } + local NW : word count `refweight' + if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:refw}eight()} accepts only " /// + "one variable{p_end}" + exit 198 + } + cap confirm numeric variable `refweight', exact + if _rc { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:refw}eight()} accepts " /// + "only numeric variables{p_end}" + exit 7 + } +} + +/* Check option size() */ +if ("`size'" != "") { + local NW : word count `size' + if (`NW' != 1) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:si}ze()} accepts only 1 " /// + "argument{p_end}" + exit 198 + } + cap confirm number `size' + if _rc { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:si}ze()} accepts only " /// + "numbers{p_end}" + exit 7 + } + if (`size' <= 0) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "the argument of suboption {bf:{ul:si}ze()} " /// + "must be >0{p_end}" + exit 198 + } +} + +/* Check option legenda() */ +if ("`legenda'" != "") { + local LIST "on off" + local EXIST : list posof "`legenda'" in LIST + if !`EXIST' { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:legenda}()} accepts only one " /// + "of the following keywords: {bf:`LIST'}{p_end}" + exit 198 + } +} + +/* Check option legshow() */ +if ("`legenda'" == "on") & ("`legshow'" != "") { + cap numlist "`legshow'" + if _rc { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "invalid numlist in suboption " /// + "{bf:{ul:legs}how()}{p_end}" + exit 121 + } +} + +/* Marksample */ +marksample TOUSE +markout `TOUSE' `variables' `xcoord' `ycoord' +if ("`by'" != "") markout `TOUSE' `by' +if ("`proportional'" != "") markout `TOUSE' `proportional' +if ("`refweight'" != "" & "`type'" == "frect") { + markout `TOUSE' `refweight' +} +qui count if `TOUSE' +if (r(N) == 0) error 2000 + + + + +* ---------------------------------------------------------------------------- +* 4. Define basic objects +* ---------------------------------------------------------------------------- + +/* Select relevant observations */ +qui keep if `TOUSE' + +/* Count observations */ +qui count +local OBS = r(N) + + +/* Set defaults relevant only when proportional != "" */ +if ("`proportional'" != "") { + + /* Set default range for weighting variable normalization */ + if ("`prange'" == "") { + qui su `proportional', meanonly + local prange "0 `r(max)'" + } + + /* Set min-max values for weighting variable normalization */ + local PMIN : word 1 of `prange' + local PMAX : word 2 of `prange' + +/* End */ +} + + +/* Set defaults relevant only when type(frect) */ +if ("`type'" == "frect") { + + /* Set default range for attribute variable normalization */ + if ("`range'" == "") { + qui su `variables', meanonly + local range "0 `r(max)'" + } + + /* Set min-max values for attribute variable normalization */ + local VMIN : word 1 of `range' + local VMAX : word 2 of `range' + + /* Set default reference value */ + if ("`refval'" == "") local refval "mean" + + /* Set STAT corresponding to specified reference value */ + if ("`refval'" == "mean") local STAT "mean" + if ("`refval'" == "median") local STAT "p50" + + /* Set reference weight */ + if ("`refweight'" != "") local REFWEIGHT "[aweight = `refweight']" + + /* Set default reference line color */ + if (`"`refcolor'"' == "") local refcolor "black" + + /* Set default reference line thickness */ + if (`"`refsize'"' == "") local refsize "medium" + +/* End */ +} + + +/* Set default baseline size */ +if ("`size'" == "") local size = 1 + +/* Set default fill color */ +local fcolor_d "black" +if (`NVAR' == 1) { + if (`"`fcolor'"' == "") local fcolor "`fcolor_d' ..." +} +else { + if (`"`fcolor'"' == "") { + local fcolor "red blue orange green lime navy sienna ltblue cranberry" + local fcolor "`fcolor' emerald eggshell magenta olive brown yellow" + local fcolor "`fcolor' dkgreen" + } +} + +/* Set default outline color */ +local ocolor_d "black" +if (`"`ocolor'"' == "") local ocolor "`ocolor_d' ..." + +/* Set default outline thickness */ +local osize_d "thin" +if ("`osize'" == "") local osize "`osize_d' ..." + +/* Set default outline thickness */ +local oalign_d "center" +if ("`oalign'" == "") local oalign "`oalign_d' ..." + + +/* Set default legend */ +if ("`legenda'" == "") local legenda "off" + +/* Set legend title when legtitle(varlab) */ +if ("`legenda'" == "on") & (`NVAR' == 1) & (`"`legtitle'"' == "varlab") { + local legtitle : variable label `variables' + if (`"`legtitle'"' == "") local legtitle "`variables'" +} + + + + +* ---------------------------------------------------------------------------- +* 5. Create working dataset and return info of interest: framed rect. chart +* ---------------------------------------------------------------------------- + +/* Start condition */ +if ("`type'" == "frect") { + + +/* Housekeeping */ +cap drop __DIA* + +/* Compute reference value */ +if ("`RVTYPE'" == "NUM") local RV = `refval' +else { + qui su `variables' `REFWEIGHT', detail + local RV = (r(`STAT') - `VMIN') / (`VMAX' - `VMIN') +} + +/* Generate coordinate variables */ +tempvar X Y +qui gen `X' = `xcoord' +qui gen `Y' = `ycoord' + +/* Generate main variable (normalized) */ +tempvar V +qui clonevar `V' = `variables' +qui replace `V' = (`V' - `VMIN') / (`VMAX' - `VMIN') +local VARLAB : variable label `V' +if (`"`VARLAB'"' == "") local VARLAB "`V'" + +/* Generate group variable */ +tempvar G +if ("`by'" == "") qui gen `G' = 1 +if ("`by'" != "") qui egen `G' = group(`by'), label +qui tab `G' +local NG = r(r) + +/* Count objects */ +if ("`legenda'" == "on") & ("`legcount'" != "") { + forval i = 1/`NG' { + qui count if `G' == `i' + local COUNT "`COUNT'`r(N)' " + } +} + +/* Set list of available color palettes */ +local PALETTE "`PALETTE' Accent Blues BrBG BuGn BuPu Dark2 GnBu Greens Greys" +local PALETTE "`PALETTE' OrRd Oranges PRGn Paired Pastel1 Pastel2 PiYG PuBu" +local PALETTE "`PALETTE' PuBuGn PuOr PuRd Purples RdBu RdGy RdPu RdYlBu" +local PALETTE "`PALETTE' RdYlGn Reds Set1 Set2 Set3 Spectral YlGn YlGnBu" +local PALETTE "`PALETTE' YlOrBr YlOrRd" +local PALETTE "`PALETTE' BuRd BuYlRd Heat Terrain Topological" +local PALETTE "`PALETTE' Blues2 Greens2 Greys2 Reds2 Rainbow" + +/* Parse option fcolor() */ +local EXIST : list posof `"`fcolor'"' in PALETTE +if `EXIST' { + if (`NG' > 1) { + spmap_color "`fcolor'" `NG' + local fcolor `"`s(colors)'"' + } + else { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "when no group variable is specified in suboption " /// + "{bf:{ul:by}()}, suboption {bf:{ul:fc}olor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`fcolor') m(`NG') o({bf:{ul:fc}olor()}) d(`fcolor_d') + local fcolor `"`s(pl)'"' +} + +spmap_psl, l(`oalign') m(`NG') o({bf:{ul:oa}liagn()}) d(`oalign_d') +local oalign `"`s(pl)'"' + +/* Parse option ocolor() */ +local EXIST : list posof `"`ocolor'"' in PALETTE +if `EXIST' { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "when suboption {bf:{ul:t}ype(frect)} is " /// + "specified, suboption {bf:{ul:oc}olor()} " /// + "does not accept palette names{p_end}" + exit 198 +} +local ocolor : word 1 of `ocolor' + +/* Parse option osize() */ +local osize : word 1 of `osize' + +/* Parse option refcolor() */ +local refcolor : word 1 of `refcolor' + +/* Parse option refsize() */ +local refsize : word 1 of `refsize' + +/* Generate weighting variable */ +tempvar W +if ("`proportional'" == "") qui gen `W' = 1 +if ("`proportional'" != "") { + qui gen `W' = (`proportional' - `PMIN') / (`PMAX' - `PMIN') +} +gsort -`W' + +/* Keep relevant variables */ +keep `X' `Y' `V' `G' `W' + +/* Set baseline rectangle dimension */ +qui su `X', meanonly +local xd = `r(max)' - `r(min)' +qui su `Y', meanonly +local yd = `r(max)' - `r(min)' +local U = sqrt( (`xd' * `yd') / (`OBS' * 2) ) +local XL = (`U' / 4) * `size' +local YL = (`U' / 2) * `size' + +/* Expand dataset */ +local NOBS = `OBS' * 18 +qui set obs `NOBS' + +/* Generate new variables */ +qui gen __DIA_G = . +qui gen __DIA_X = . +qui gen __DIA_Y = . + +/* Fill new variables */ +local r = 1 +forval i = 1/`OBS' { + local Xi = `X'[`i'] + local Yi = `Y'[`i'] + local Vi = `V'[`i'] + local Gi = `G'[`i'] + local Wi = `W'[`i'] + local X0 = `Xi' - ((`XL'*`Wi') / 2) + local Y0 = `Yi' - (`YL' / 2) + + qui replace __DIA_G = 0 in `r' + local r = `r' + 1 + qui replace __DIA_G = 0 in `r' + qui replace __DIA_X = `X0' in `r' + qui replace __DIA_Y = (`Y0' + `YL'*`Vi') in `r' + local r = `r' + 1 + qui replace __DIA_G = 0 in `r' + qui replace __DIA_X = `X0' in `r' + qui replace __DIA_Y = (`Y0' + `YL') in `r' + local r = `r' + 1 + qui replace __DIA_G = 0 in `r' + qui replace __DIA_X = (`X0' + `XL'*`Wi') in `r' + qui replace __DIA_Y = (`Y0' + `YL') in `r' + local r = `r' + 1 + qui replace __DIA_G = 0 in `r' + qui replace __DIA_X = (`X0' + `XL'*`Wi') in `r' + qui replace __DIA_Y = (`Y0' + `YL'*`Vi') in `r' + local r = `r' + 1 + + qui replace __DIA_G = `Gi' in `r' + local r = `r' + 1 + qui replace __DIA_G = `Gi' in `r' + qui replace __DIA_X = `X0' in `r' + qui replace __DIA_Y = `Y0' in `r' + local r = `r' + 1 + qui replace __DIA_G = `Gi' in `r' + qui replace __DIA_X = `X0' in `r' + qui replace __DIA_Y = (`Y0' + `YL'*`Vi') in `r' + local r = `r' + 1 + qui replace __DIA_G = `Gi' in `r' + qui replace __DIA_X = (`X0' + `XL'*`Wi') in `r' + qui replace __DIA_Y = (`Y0' + `YL'*`Vi') in `r' + local r = `r' + 1 + qui replace __DIA_G = `Gi' in `r' + qui replace __DIA_X = (`X0' + `XL'*`Wi') in `r' + qui replace __DIA_Y = `Y0' in `r' + local r = `r' + 1 + + qui replace __DIA_G = 998 in `r' + local r = `r' + 1 + qui replace __DIA_G = 998 in `r' + qui replace __DIA_X = `X0' in `r' + qui replace __DIA_Y = `Y0' in `r' + local r = `r' + 1 + qui replace __DIA_G = 998 in `r' + qui replace __DIA_X = `X0' in `r' + qui replace __DIA_Y = (`Y0' + `YL') in `r' + local r = `r' + 1 + qui replace __DIA_G = 998 in `r' + qui replace __DIA_X = (`X0' + `XL'*`Wi') in `r' + qui replace __DIA_Y = (`Y0' + `YL') in `r' + local r = `r' + 1 + qui replace __DIA_G = 998 in `r' + qui replace __DIA_X = (`X0' + `XL'*`Wi') in `r' + qui replace __DIA_Y = `Y0' in `r' + local r = `r' + 1 + + qui replace __DIA_G = 999 in `r' + local r = `r' + 1 + qui replace __DIA_G = 999 in `r' + qui replace __DIA_X = (`X0' - (`XL'*`Wi')/4) in `r' + qui replace __DIA_Y = (`Y0' + `YL'*`RV') in `r' + local r = `r' + 1 + qui replace __DIA_G = 999 in `r' + qui replace __DIA_X = (`X0' + `XL'*`Wi'*1.25) in `r' + qui replace __DIA_Y = (`Y0' + `YL'*`RV') in `r' + local r = `r' + 1 +} + +/* Save dataset */ +qui clonevar __DIA_LBL = `G' +keep __DIA* +qui save "__DIA.dta", replace + +if c(stata_version) >= 15 { + local LA la(center) +} + +/* Compose command */ +local GRAPH `"`GRAPH'(area __DIA_Y __DIA_X if __DIA_G == 0, nodropbase"' +local GRAPH `"`GRAPH' cmissing(n) fc("white") lc("white") lw("none") `LA') "' +forval i = 1/`NG' { + local FC : word `i' of `fcolor' + local OA : word `i' of `oalign' + if c(stata_version) >= 15 { + local LA `"la("`OA'")"' + } + local GRAPH `"`GRAPH'(area __DIA_Y __DIA_X if __DIA_G == `i', nodropbase"' + local GRAPH `"`GRAPH' cmissing(n) fc("`FC'") fi(100) lc("`FC'")"' + local GRAPH `"`GRAPH' lw("none") `LA') "' +} +local OC : word 1 of `ocolor' +local OS : word 1 of `osize' +local OA : word 1 of `oalign' +if c(stata_version) >= 15 { + local LA `"la("`OA'")"' +} +local GRAPH `"`GRAPH'(area __DIA_Y __DIA_X if __DIA_G == 998, nodropbase"' +local GRAPH `"`GRAPH' cmissing(n) fc("none") lc("`OC'") lw("`OS'") `LA') "' +local RC : word 1 of `refcolor' +local RS : word 1 of `refsize' +local GRAPH `"`GRAPH'(line __DIA_Y __DIA_X if __DIA_G == 999, nodropbase"' +local GRAPH `"`GRAPH' cmissing(n) fc("none") lc("`RC'") lw("`RS'")) "' + +/* Set number of keys */ +local NK = 1 + `NG' + 2 + +/* Set legend when legenda(off) */ +if ("`legenda'" == "off") { + local TITLE "" + local KEY "" + local LABEL "" +} + +/* Set legend when legenda(on) */ +if ("`legenda'" == "on") { + if ("`by'" == "") { + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + local KEY "2 " + if ("`legcount'" == "") { + local LABEL `"`LABEL'`"`VARLAB'"' "' + } + else { + local OBS : word 1 of `COUNT' + local LABEL `"`LABEL'`"`VARLAB' (`OBS')"' "' + } + } + else { + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + numlist "2/`=`NG'+1'" + local KEY "`r(numlist)'" + if ("`legshow'" != "") { + local CHECK : list legshow in KEY + if !`CHECK' { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "one or more keys specified in suboption " /// + "{bf:{ul:legs}how()} do not exist. Valid keys " /// + " are: `KEY'{p_end}" + exit 198 + } + else local KEY "`legshow'" + } + foreach K in `KEY' { + local K = `K' - 1 + local LBL : label (__DIA_LBL) `K' + if ("`legcount'" == "") { + local LABEL `"`LABEL'`"`LBL'"' "' + } + else { + local OBS : word `K' of `COUNT' + local LABEL `"`LABEL'`"`LBL' (`OBS')"' "' + } + } + } +} + +/* Return command */ +return local command `"`GRAPH'"' + +/* Return min/max coordinates */ +qui summ __DIA_X +return local xmin=r(min) +return local xmax=r(max) +qui summ __DIA_Y +return local ymin=r(min) +return local ymax=r(max) + +/* Return legend info */ +return local title `"`TITLE'"' +return local key `"`KEY'"' +return local label `"`LABEL'"' +return local nk = `NK' + + +/* End condition */ +} + + + + +* ---------------------------------------------------------------------------- +* 6. Create working dataset and return info of interest: pie chart +* ---------------------------------------------------------------------------- + +/* Start condition */ +if ("`type'" == "pie") { + + +/* Housekeeping */ +cap drop __DIA* + +/* Generate coordinate variables */ +tempvar X Y +qui gen `X' = `xcoord' +qui gen `Y' = `ycoord' + +/* Generate main variables (percentage form) */ +tempvar TOT +qui egen `TOT' = rsum(`variables') +forval i = 1/`NVAR' { + local V : word `i' of `variables' + tempvar V`i' + qui clonevar `V`i'' = `V' + qui replace `V`i'' = round((`V`i'' / `TOT') * 100) + local VARLIST "`VARLIST'`V`i'' " + local VARLAB : variable label `V' + if (`"`VARLAB'"' == "") local VARLAB "`V'" + local LBLS `"`LBLS'`"`VARLAB'"' "' +} + +/* Generate weighting variable */ +tempvar W +if ("`proportional'" == "") qui gen `W' = 1 +if ("`proportional'" != "") { + qui gen `W' = (`proportional' - `PMIN') / (`PMAX' - `PMIN') +} +qui su `W' +local WMAX = r(max) +gsort -`W' + +/* Create working matrices */ +tempname DATA VARS +mkmat `X' `Y' `W', matrix(`DATA') +mkmat `VARLIST', matrix(`VARS') + +/* Set baseline pie radius */ +qui su `X', meanonly +local xd = `r(max)' - `r(min)' +qui su `Y', meanonly +local yd = `r(max)' - `r(min)' +local RAD = sqrt( (`xd' * `yd') / (`OBS' * 2) ) +local RAD = (`RAD' / 4) * `size' + +/* Create working dataset */ +forval i = 1/`OBS' { + drop _all + qui set obs 101 + + local Xi = `DATA'[`i',1] + local Yi = `DATA'[`i',2] + local Wi = `DATA'[`i',3] + + qui gen __DIA_X = sin(2 * _pi * (_n-1)/100) + qui gen __DIA_Y = cos(2 * _pi * (_n-1)/100) + qui replace __DIA_X = `Xi' + (__DIA_X * `RAD' * (`Wi'/`WMAX')^(0.57)) + qui replace __DIA_Y = `Yi' + (__DIA_Y * `RAD' * (`Wi'/`WMAX')^(0.57)) + tempfile PIE + qui save `"`PIE'"', replace + + local INF "" + local SUP "" + local CUM = 1 + local NJ = 0 + local VJ "" + forval j = 1/`NVAR' { + local PCT = `VARS'[`i',`j'] + if (`PCT' > 0) { + local INF "`INF'`CUM' " + local CUM = `CUM' + `PCT' + if (`j' == `NVAR') local CUM = "101" + local SUP "`SUP'`CUM' " + local NJ = `NJ' + 1 + local VJ "`VJ'`j' " + } + } + + forval j = 1/`NJ' { + use `"`PIE'"', clear + local FROM : word `j' of `INF' + local TO : word `j' of `SUP' + qui keep in `FROM'/`TO' + qui gen SORT = _n + 2 + qui count + local OBSj = r(N) + 3 + qui set obs `OBSj' + qui replace SORT = 1 in `= r(N) + 1' + qui replace SORT = 2 in `= r(N) + 2' + qui replace SORT = `OBSj' in `= r(N) + 3' + qui replace __DIA_X = `Xi' in `= r(N) + 2' + qui replace __DIA_Y = `Yi' in `= r(N) + 2' + qui replace __DIA_X = `Xi' in `= r(N) + 3' + qui replace __DIA_Y = `Yi' in `= r(N) + 3' + sort SORT + local VAR : word `j' of `VJ' + qui gen __DIA_G = `VAR' + tempfile TEMP`j' + qui save `"`TEMP`j''"', replace + } + + use `"`TEMP1'"', clear + forval j = 2/`NJ' { + qui append using `"`TEMP`j''"' + } + + tempfile PIE`i' + qui save `"`PIE`i''"', replace +} + +use `"`PIE1'"', clear +forval i = 2/`OBS' { + qui append using `"`PIE`i''"' +} + +/* Save dataset */ +keep __DIA* +qui save "__DIA.dta", replace + +/* Set list of available color palettes */ +local PALETTE "`PALETTE' Accent Blues BrBG BuGn BuPu Dark2 GnBu Greens Greys" +local PALETTE "`PALETTE' OrRd Oranges PRGn Paired Pastel1 Pastel2 PiYG PuBu" +local PALETTE "`PALETTE' PuBuGn PuOr PuRd Purples RdBu RdGy RdPu RdYlBu" +local PALETTE "`PALETTE' RdYlGn Reds Set1 Set2 Set3 Spectral YlGn YlGnBu" +local PALETTE "`PALETTE' YlOrBr YlOrRd" +local PALETTE "`PALETTE' BuRd BuYlRd Heat Terrain Topological" +local PALETTE "`PALETTE' Blues2 Greens2 Greys2 Reds2 Rainbow" + +/* Parse option fcolor() */ +local EXIST : list posof `"`fcolor'"' in PALETTE +if `EXIST' { + if (`NVAR' > 1) { + spmap_color "`fcolor'" `NVAR' + local fcolor `"`s(colors)'"' + } + else { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "when only one variable is specified in suboption " /// + "{bf:{ul:v}ariables()}, suboption {bf:{ul:fc}olor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`fcolor') m(`NVAR') o({bf:{ul:fc}olor()}) d(`fcolor_d') + local fcolor `"`s(pl)'"' +} + +/* Parse option ocolor() */ +local EXIST : list posof `"`ocolor'"' in PALETTE +if `EXIST' { + if (`NVAR' > 1) { + spmap_color "`ocolor'" `NVAR' + local ocolor `"`s(colors)'"' + } + else { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "when only one variable is specified in suboption " /// + "{bf:{ul:v}ariables()}, suboption {bf:{ul:oc}olor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`ocolor') m(`NVAR') o({bf:{ul:oc}olor()}) d(`ocolor_d') + local ocolor `"`s(pl)'"' +} + +/* Parse option osize() */ +spmap_psl, l(`osize') m(`NVAR') o({bf:{ul:os}ize()}) d(`osize_d') +local osize `"`s(pl)'"' + +/* Parse option oalign() */ +spmap_psl, l(`oalign') m(`NVAR') o({bf:{ul:os}ize()}) d(`oalign_d') +local oalign `"`s(pl)'"' + +/* Compose command */ +forval i = 1/`NVAR' { + local FC : word `i' of `fcolor' + local OC : word `i' of `ocolor' + if ("`OC'" == "none") local OC "`FC'" + local OS : word `i' of `osize' + local OA : word `i' of `oalign' + if c(stata_version) >= 15 { + local LA `"la("`OA'")"' + } + local GRAPH `"`GRAPH'(area __DIA_Y __DIA_X if __DIA_G == `i', nodropbase"' + local GRAPH `"`GRAPH' cmissing(n) fc("`FC'") fi(100) lc("`OC'")"' + local GRAPH `"`GRAPH' lw("`OS'") `LA') "' +} + +/* Set number of keys */ +local NK = `NVAR' + +/* Set legend when legenda(off) */ +if ("`legenda'" == "off") { + local TITLE "" + local KEY "" + local LABEL "" +} + +/* Set legend when legenda(on) */ +if ("`legenda'" == "on") { + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + numlist "1/`NVAR'" + local KEY "`r(numlist)'" + if ("`legshow'" != "") { + local CHECK : list legshow in KEY + if !`CHECK' { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "one or more keys specified in suboption " /// + "{bf:{ul:legs}how()} do not exist. Valid keys " /// + " are: `KEY'{p_end}" + exit 198 + } + else local KEY "`legshow'" + } + foreach K in `KEY' { + local LBL : word `K' of `LBLS' + local LABEL `"`LABEL'`"`LBL'"' "' + } +} + +/* Return command */ +return local command `"`GRAPH'"' + +/* Return min/max coordinates */ +qui summ __DIA_X +return local xmin = r(min) +return local xmax = r(max) +qui summ __DIA_Y +return local ymin = r(min) +return local ymax = r(max) + +/* Return legend info */ +return local title `"`TITLE'"' +return local key `"`KEY'"' +return local label `"`LABEL'"' +return local nk = `NK' + + +/* End condition */ +} + + + + +* ---------------------------------------------------------------------------- +* 7. End program +* ---------------------------------------------------------------------------- + +restore +end + + + diff --git a/notebooks/msna/Codes/ado/s/spmap_examples.ado b/notebooks/msna/Codes/ado/s/spmap_examples.ado new file mode 100644 index 00000000..fd20aa79 --- /dev/null +++ b/notebooks/msna/Codes/ado/s/spmap_examples.ado @@ -0,0 +1,328 @@ +*! -spmap_examples-: Auxiliary program for -spmap- +*! Version 1.3.0 - 13 March 2017 +*! Version 1.2.0 - 14 March 2008 +*! Version 1.1.0 - 7 May 2007 +*! Version 1.0.0 - 7 December 2006 +*! Author: Maurizio Pisati +*! Department of Sociology and Social Research +*! University of Milano Bicocca (Italy) +*! maurizio.pisati@unimib.it + + + + +* ---------------------------------------------------------------------------- +* 1. Main program +* ---------------------------------------------------------------------------- + +program spmap_examples +version 9.2 +args EXAMPLE +set more off +`EXAMPLE' +end + + + + +* ---------------------------------------------------------------------------- +* 2. Choropleth maps +* ---------------------------------------------------------------------------- + +program chomap01 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) +end + +program chomap02 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) +end + +program chomap03 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(2) legend(region(lcolor(black))) +end + +program chomap04 +sysuse "Italy-RegionsData.dta", clear +spmap relig1m using "Italy-RegionsCoordinates.dta", id(id) /// + ndfcolor(red) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(2) legend(region(lcolor(black))) +end + +program chomap05 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clmethod(eqint) clnumber(5) eirange(20 70) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(2) legend(region(lcolor(black))) +end + +program chomap06 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Reds2) ocolor(none ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) +end + +program chomap07 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Reds2) ocolor(none ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) legend(ring(1) position(3)) +end + +program chomap08 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Reds2) ocolor(none ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) legend(ring(1) position(3)) /// + plotregion(margin(vlarge)) +end + +program chomap09 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Reds2) ocolor(none ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) legend(ring(1) position(3)) /// + plotregion(icolor(stone)) graphregion(icolor(stone)) +end + +program chomap10 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Greens2) ocolor(white ..) osize(medthin ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) legend(ring(1) position(3)) /// + plotregion(icolor(stone)) graphregion(icolor(stone)) +end + +program chomap11 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Greens2) ocolor(white ..) osize(thin ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) legend(ring(1) position(3)) /// + plotregion(icolor(stone)) graphregion(icolor(stone)) /// + polygon(data("Italy-Highlights.dta") ocolor(white) /// + osize(medthick)) +end + +program chomap12 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clnumber(20) fcolor(Greens2) ocolor(white ..) osize(medthin ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + legstyle(3) legend(ring(1) position(3)) /// + plotregion(icolor(stone)) graphregion(icolor(stone)) /// + scalebar(units(500) scale(1/1000) xpos(-100) label(Kilometers)) +end + + + + +* ---------------------------------------------------------------------------- +* 3. Proportional symbol maps +* ---------------------------------------------------------------------------- + +program prsmap01 +sysuse "Italy-OutlineData.dta", clear +spmap using "Italy-OutlineCoordinates.dta", id(id) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) proportional(relig1) fcolor(red) size(*1.5)) +end + +program prsmap02 +sysuse "Italy-OutlineData.dta", clear +spmap using "Italy-OutlineCoordinates.dta", id(id) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) proportional(relig1) fcolor(red) size(*1.5) /// + shape(s)) +end + +program prsmap03 +sysuse "Italy-OutlineData.dta", clear +spmap using "Italy-OutlineCoordinates.dta", id(id) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) proportional(relig1) fcolor(red) /// + ocolor(white) size(*3)) /// + label(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) label(relig1) color(white) size(*0.7)) +end + +program prsmap04 +sysuse "Italy-OutlineData.dta", clear +spmap using "Italy-OutlineCoordinates.dta", id(id) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) deviation(relig1) fcolor(red) dmax(30) /// + legenda(on) leglabel(Deviation from the mean)) +end + +program prsmap05 +sysuse "Italy-OutlineData.dta", clear +spmap using "Italy-OutlineCoordinates.dta", id(id) fcolor(white) /// + title("Catholics without reservations", size(*0.9) box bexpand /// + span margin(medsmall) fcolor(sand)) subtitle(" ") /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) proportional(relig1) prange(0 70) /// + psize(absolute) fcolor(red) ocolor(white) size(*0.6)) /// + plotregion(margin(medium) color(stone)) /// + graphregion(fcolor(stone) lcolor(black)) /// + name(g1, replace) nodraw +spmap using "Italy-OutlineCoordinates.dta", id(id) fcolor(white) /// + title("Catholics with reservations", size(*0.9) box bexpand /// + span margin(medsmall) fcolor(sand)) subtitle(" ") /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) proportional(relig2) prange(0 70) /// + psize(absolute) fcolor(green) ocolor(white) size(*0.6)) /// + plotregion(margin(medium) color(stone)) /// + graphregion(fcolor(stone) lcolor(black)) /// + name(g2, replace) nodraw +spmap using "Italy-OutlineCoordinates.dta", id(id) fcolor(white) /// + title("Other", size(*0.9) box bexpand /// + span margin(medsmall) fcolor(sand)) subtitle(" ") /// + point(data("Italy-RegionsData.dta") xcoord(xcoord) /// + ycoord(ycoord) proportional(relig3) prange(0 70) /// + psize(absolute) fcolor(blue) ocolor(white) size(*0.6)) /// + plotregion(margin(medium) color(stone)) /// + graphregion(fcolor(stone) lcolor(black)) /// + name(g3, replace) nodraw +graph combine g1 g2 g3, rows(1) title("Religious orientation") /// + subtitle("Italy, 1994-98" " ") xsize(5) ysize(2.6) /// + plotregion(margin(medsmall) style(none)) /// + graphregion(margin(zero) style(none)) /// + scheme(s1mono) +end + + + + +* ---------------------------------------------------------------------------- +* 4. Other maps +* ---------------------------------------------------------------------------- + +program othmap01 +sysuse "Italy-RegionsData.dta", clear +spmap using "Italy-RegionsCoordinates.dta", id(id) fcolor(stone) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) /// + diagram(variable(relig1) range(0 100) refweight(pop98) /// + xcoord(xcoord) ycoord(ycoord) fcolor(red)) +end + +program othmap02 +sysuse "Italy-RegionsData.dta", clear +spmap using "Italy-RegionsCoordinates.dta", id(id) fcolor(stone) /// + diagram(variable(relig1 relig2 relig3) proportional(fortell) /// + xcoord(xcoord) ycoord(ycoord) legenda(on)) /// + legend(title("Religious orientation", size(*0.5) bexpand /// + justification(left))) /// + note(" " /// + "NOTE: Chart size proportional to number of fortune tellers per million population", /// + size(*0.75)) +end + +program othmap03 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clmethod(stdev) clnumber(5) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) area(pop98) /// + note(" " /// + "NOTE: Region size proportional to population", size(*0.75)) +end + +program othmap04 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta", id(id) /// + clmethod(stdev) clnumber(5) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Italy, 1994-98" " ", size(*0.8)) area(pop98) /// + map("Italy-OutlineCoordinates.dta") mfcolor(stone) /// + note(" " /// + "NOTE: Region size proportional to population", size(*0.75)) +end + +program othmap05 +sysuse "Italy-OutlineData.dta", clear +spmap using "Italy-OutlineCoordinates.dta", id(id) fc(bluishgray) /// + ocolor(none) /// + title("Provincial capitals" " ", size(*0.9) color(white)) /// + point(data("Italy-Capitals.dta") xcoord(xcoord) /// + ycoord(ycoord) fcolor(emerald)) /// + plotregion(margin(medium) icolor(dknavy) color(dknavy)) /// + graphregion(icolor(dknavy) color(dknavy)) +end + +program othmap06 +sysuse "Italy-OutlineData.dta", clear +spmap using "Italy-OutlineCoordinates.dta", id(id) fc(bluishgray) /// + ocolor(none) /// + title("Provincial capitals" " ", size(*0.9) color(white)) /// + point(data("Italy-Capitals.dta") xcoord(xcoord) /// + ycoord(ycoord) by(size) fcolor(orange red maroon) shape(s ..) /// + legenda(on)) /// + legend(title("Population 1998", size(*0.5) bexpand /// + justification(left)) region(lcolor(black) fcolor(white)) /// + position(2)) /// + plotregion(margin(medium) icolor(dknavy) color(dknavy)) /// + graphregion(icolor(dknavy) color(dknavy)) +end + +program othmap07 +sysuse "Italy-OutlineData.dta", clear +spmap using "Italy-OutlineCoordinates.dta", id(id) fc(sand) /// + title("Main lakes and rivers" " ", size(*0.9)) /// + polygon(data("Italy-Lakes.dta") fcolor(blue) ocolor(blue)) /// + line(data("Italy-Rivers.dta") color(blue) ) +end + +program othmap08 +sysuse "Italy-RegionsData.dta", clear +spmap relig1 using "Italy-RegionsCoordinates.dta" if zone==1, id(id) /// + fcolor(Blues2) ocolor(white ..) osize(medthin ..) /// + title("Pct. Catholics without reservations", size(*0.8)) /// + subtitle("Northern Italy, 1994-98" " ", size(*0.8)) /// + polygon(data("Italy-OutlineCoordinates.dta") fcolor(gs12) /// + ocolor(white) osize(medthin)) polyfirst +end + +program othmap09 +sysuse "Italy-OutlineData.dta", clear +spmap using "Italy-OutlineCoordinates.dta", id(id) fc(sand) /// + title("Main lakes and rivers" " ", size(*0.9)) /// + polygon(data("Italy-Lakes.dta") fcolor(blue) ocolor(blue)) /// + line(data("Italy-Rivers.dta") color(blue) ) /// + freestyle aspect(1.4) xlab(400000 900000 1400000, grid) +end + + + diff --git a/notebooks/msna/Codes/ado/s/spmap_label.ado b/notebooks/msna/Codes/ado/s/spmap_label.ado new file mode 100644 index 00000000..485c3fee --- /dev/null +++ b/notebooks/msna/Codes/ado/s/spmap_label.ado @@ -0,0 +1,437 @@ +*! -spmap_label-: Auxiliary program for -spmap- +*! Version 1.3.0 - 13 March 2017 +*! Version 1.2.0 - 14 March 2008 +*! Version 1.1.0 - 7 May 2007 +*! Version 1.0.0 - 7 December 2006 +*! Author: Maurizio Pisati +*! Department of Sociology and Social Research +*! University of Milano Bicocca (Italy) +*! maurizio.pisati@unimib.it + + + + +* ---------------------------------------------------------------------------- +* 1. Define program +* ---------------------------------------------------------------------------- + +program spmap_label, rclass +version 9.2 + + + + +* ---------------------------------------------------------------------------- +* 2. Define syntax +* ---------------------------------------------------------------------------- + +syntax, [Data(string)] /// + [Select(string asis)] /// + [BY(string)] /// + /// + [Xcoord(string)] /// + [Ycoord(string)] /// + [Label(string)] /// + /// + [LEngth(string)] /// + [SIze(string)] /// + [COlor(string asis)] /// + [POsition(string)] /// + [GAp(string)] /// + [ANgle(string)] + + + + +* ---------------------------------------------------------------------------- +* 3. Check syntax +* ---------------------------------------------------------------------------- + +/* Preserve data */ +preserve + +/* Check and open dataset */ +if ("`data'" != "") { + if (substr(reverse("`data'"),1,4) != "atd.") { + local data "`data'.dta" + } + capture confirm file "`data'" + if _rc { + di as err "{p}Problem with option {bf:{ul:lab}el()}: file " /// + "{bf:`data'} specified in suboption {bf:{ul:d}ata()} " /// + "not found{p_end}" + exit 601 + } + use "`data'", clear +} + +/* Select relevant records */ +if (`"`select'"' != "") { + cap `select' + if _rc { + di as err "{p}Problem with option {bf:{ul:lab}el()}: suboption " /// + "{bf:{ul:s}elect()} specified incorrectly{p_end}" + exit 198 + } +} + +/* Check option by() */ +if ("`by'" != "") { + cap unab by : `by' + if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "variable {bf:`by'} specified in suboption " /// + "{bf:{ul:by}()} not found{p_end}" + exit 111 + } + if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "string {bf:`by'} specified in suboption " /// + "{bf:{ul:by}()} is not a valid variable " /// + "name{p_end}" + exit 198 + } + local NW : word count `by' + if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "suboption {bf:{ul:by}()} accepts only one " /// + "variable{p_end}" + exit 198 + } +} + +/* Check option xcoord() */ +if ("`xcoord'" == "") { + di as err "{p}Problem with option {bf:{ul:lab}el()}: suboption " /// + "{bf:{ul:x}coord()} is required{p_end}" + exit 198 +} +cap unab xcoord : `xcoord' +if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "variable {bf:`xcoord'} specified in suboption " /// + "{bf:{ul:x}coord()} not found{p_end}" + exit 111 +} +if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "string {bf:`xcoord'} specified in suboption " /// + "{bf:{ul:x}coord()} is not a valid variable " /// + "name{p_end}" + exit 198 +} +local NW : word count `xcoord' +if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "suboption {bf:{ul:x}coord()} accepts only one " /// + "variable{p_end}" + exit 198 +} +cap confirm numeric variable `xcoord', exact +if _rc { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "suboption {bf:{ul:x}coord()} accepts only " /// + "numeric variables{p_end}" + exit 7 +} + +/* Check option ycoord() */ +if ("`ycoord'" == "") { + di as err "{p}Problem with option {bf:{ul:lab}el()}: suboption " /// + "{bf:{ul:y}coord()} is required{p_end}" + exit 198 +} +cap unab ycoord : `ycoord' +if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "variable {bf:`ycoord'} specified in suboption " /// + "{bf:{ul:y}coord()} not found{p_end}" + exit 111 +} +if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "string {bf:`ycoord'} specified in suboption " /// + "{bf:{ul:y}coord()} is not a valid variable " /// + "name{p_end}" + exit 198 +} +local NW : word count `ycoord' +if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "suboption {bf:{ul:y}coord()} accepts only one " /// + "variable{p_end}" + exit 198 +} +cap confirm numeric variable `ycoord', exact +if _rc { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "suboption {bf:{ul:y}coord()} accepts only " /// + "numeric variables{p_end}" + exit 7 +} + +/* Check option label() */ +if ("`label'" == "") { + di as err "{p}Problem with option {bf:{ul:lab}el()}: suboption " /// + "{bf:{ul:l}abel()} is required{p_end}" + exit 198 +} +cap unab label : `label' +if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "variable {bf:`label'} specified in suboption " /// + "{bf:{ul:l}abel()} not found{p_end}" + exit 111 +} +if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "string {bf:`label'} specified in suboption " /// + "{bf:{ul:l}abel()} is not a valid variable " /// + "name{p_end}" + exit 198 +} +local NW : word count `label' +if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "suboption {bf:{ul:l}abel()} accepts only one " /// + "variable{p_end}" + exit 198 +} + +/* Check option length() */ +if ("`length'" != "") { + local NW : word count `length' + forval i = 1/`NW' { + local W : word `i' of `length' + if (!inlist("`W'",".","=","..","...")) { + cap confirm number `W' + if _rc { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "suboption {bf:{ul:le}ngth()} accepts only " /// + "numbers{p_end}" + exit 7 + } + if (`W' < 1) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "suboption {bf:{ul:le}ngth()} accepts only " /// + "positive numbers{p_end}" + exit 198 + } + } + } +} + +/* Check option position() */ +if ("`position'" != "") { + local NW : word count `position' + forval i = 1/`NW' { + local W : word `i' of `position' + if (!inlist("`W'",".","=","..","...")) { + cap confirm number `W' + if _rc { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "suboption {bf:{ul:po}sition()} accepts only " /// + "numbers{p_end}" + exit 7 + } + if (`W' < 0 | `W' > 12) { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "suboption {bf:{ul:po}sition()} accepts only " /// + "numbers between 0 and 12{p_end}" + exit 198 + } + } + } +} + +/* Marksample */ +marksample TOUSE +markout `TOUSE' `label' `xcoord' `ycoord', strok +if ("`by'" != "") markout `TOUSE' `by' +qui count if `TOUSE' +if (r(N) == 0) error 2000 + + + + +* ---------------------------------------------------------------------------- +* 4. Define basic objects +* ---------------------------------------------------------------------------- + +/* Select relevant observations */ +qui keep if `TOUSE' + +/* Set default label length */ +local length_d "12" +if ("`length'" == "") local length "`length_d' ..." + +/* Set default label size */ +local size_d "*1" +if ("`size'" == "") local size "`size_d' ..." + +/* Set default label color */ +local color_d "black" +if (`"`color'"' == "") local color "`color_d' ..." + +/* Set default label position */ +local position_d "0" +if ("`position'" == "") local position "`position_d' ..." + +/* Set default label gap */ +local gap_d "*1" +if ("`gap'" == "") local gap "`gap_d' ..." + +/* Set default label angle */ +local angle_d "horizontal" +if ("`angle'" == "") local angle "`angle_d' ..." + + + + +* ---------------------------------------------------------------------------- +* 5. Create working dataset +* ---------------------------------------------------------------------------- + +/* Housekeeping */ +cap drop __LAB* + +/* Generate group variable */ +if ("`by'" == "") qui gen __LAB_G = 1 +if ("`by'" != "") qui egen __LAB_G = group(`by'), lname(__LAB_G) +qui tab __LAB_G +local NG = r(r) + +/* Parse option length() */ +spmap_psl, l(`length') m(`NG') o({bf:{ul:le}ngth()}) d(`length_d') +local length `"`s(pl)'"' + +/* Generate label variable */ +local TYPE : type `label' +local TYPE = substr("`TYPE'",1,3) +if ("`TYPE'" != "str") { + local VALLAB : value label `label' + if ("`VALLAB'" == "") { + qui tostring `label', gen(__LAB_L) force usedisplayformat + } + else { + qui decode `label', gen(__LAB_L) + } +} +else { + ren `label' __LAB_L +} +forval i = 1/`NG' { + local LEN : word `i' of `length' + qui replace __LAB_L = substr(__LAB_L , 1 , `LEN') if __LAB_G == `i' +} + +/* Generate coordinate variables */ +qui gen __LAB_X = `xcoord' +qui gen __LAB_Y = `ycoord' + +/* Save dataset */ +keep __LAB* +qui save "__LAB.dta", replace + + + + +* ---------------------------------------------------------------------------- +* 6. Parse style lists +* ---------------------------------------------------------------------------- + +/* Set list of available color palettes */ +local PALETTE "`PALETTE' Accent Blues BrBG BuGn BuPu Dark2 GnBu Greens Greys" +local PALETTE "`PALETTE' OrRd Oranges PRGn Paired Pastel1 Pastel2 PiYG PuBu" +local PALETTE "`PALETTE' PuBuGn PuOr PuRd Purples RdBu RdGy RdPu RdYlBu" +local PALETTE "`PALETTE' RdYlGn Reds Set1 Set2 Set3 Spectral YlGn YlGnBu" +local PALETTE "`PALETTE' YlOrBr YlOrRd" +local PALETTE "`PALETTE' BuRd BuYlRd Heat Terrain Topological" +local PALETTE "`PALETTE' Blues2 Greens2 Greys2 Reds2 Rainbow" + +/* Parse option size() */ +spmap_psl, l(`size') m(`NG') o({bf:{ul:si}ze()}) d(`size_d') +local size `"`s(pl)'"' + +/* Parse option color() */ +local EXIST : list posof `"`color'"' in PALETTE +if `EXIST' { + if (`NG' > 1) { + spmap_color "`color'" `NG' + local color `"`s(colors)'"' + } + else { + di as err "{p}Problem with option {bf:{ul:lab}el()}: " /// + "when no group variable is specified in suboption " /// + "{bf:{ul:by}()}, suboption {bf:{ul:co}lor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`color') m(`NG') o({bf:{ul:co}lor()}) d(`color_d') + local color `"`s(pl)'"' +} + +/* Parse option position() */ +spmap_psl, l(`position') m(`NG') o({bf:{ul:po}sition()}) d(`position_d') +local position `"`s(pl)'"' + +/* Parse option gap() */ +spmap_psl, l(`gap') m(`NG') o({bf:{ul:ga}p()}) d(`gap_d') +local gap `"`s(pl)'"' + +/* Parse option angle() */ +spmap_psl, l(`angle') m(`NG') o({bf:{ul:an}gle()}) d(`angle_d') +local angle `"`s(pl)'"' + + + + +* ---------------------------------------------------------------------------- +* 7. Compose command +* ---------------------------------------------------------------------------- + +/* Compose command */ +forval i = 1/`NG' { + local SIZ : word `i' of `size' + local COL : word `i' of `color' + local POS : word `i' of `position' + local GAP : word `i' of `gap' + local ANG : word `i' of `angle' + local GRAPH `"`GRAPH'(scatter __LAB_Y __LAB_X if __LAB_G == `i',"' + local GRAPH `"`GRAPH' mlabel(__LAB_L) mlabsize("`SIZ'") mlabcol("`COL'")"' + local GRAPH `"`GRAPH' mlabpos("`POS'") mlabgap("`GAP'") mlabang("`ANG'")"' + local GRAPH `"`GRAPH' msymbol(i)) "' +} + + + + +* ---------------------------------------------------------------------------- +* 8. Return info of interest +* ---------------------------------------------------------------------------- + +/* Return command */ +return local command `"`GRAPH'"' + +/* Return min/max coordinates */ +qui summ __LAB_X +return local xmin = r(min) +return local xmax = r(max) +qui summ __LAB_Y +return local ymin = r(min) +return local ymax = r(max) + + + + +* ---------------------------------------------------------------------------- +* 9. End program +* ---------------------------------------------------------------------------- + +restore +end + + + diff --git a/notebooks/msna/Codes/ado/s/spmap_line.ado b/notebooks/msna/Codes/ado/s/spmap_line.ado new file mode 100644 index 00000000..0d4ab075 --- /dev/null +++ b/notebooks/msna/Codes/ado/s/spmap_line.ado @@ -0,0 +1,410 @@ +*! -spmap_line-: Auxiliary program for -spmap- +*! Version 1.3.0 - 13 March 2017 +*! Version 1.2.0 - 14 March 2008 +*! Version 1.1.0 - 7 May 2007 +*! Version 1.0.0 - 7 December 2006 +*! Author: Maurizio Pisati +*! Department of Sociology and Social Research +*! University of Milano Bicocca (Italy) +*! maurizio.pisati@unimib.it + + + + +* ---------------------------------------------------------------------------- +* 1. Define program +* ---------------------------------------------------------------------------- + +program spmap_line, rclass +version 9.2 + + + + +* ---------------------------------------------------------------------------- +* 2. Define syntax +* ---------------------------------------------------------------------------- + +syntax, [Data(string)] /// + [Select(string asis)] /// + [BY(string)] /// + /// + [COlor(string asis)] /// + [SIze(string)] /// + [PAttern(string asis)] /// + /// + [LEGENDA(string)] /// + [LEGTitle(string asis)] /// + [LEGLabel(string)] /// + [LEGShow(string)] /// + [LEGCount] + + + + +* ---------------------------------------------------------------------------- +* 3. Check syntax +* ---------------------------------------------------------------------------- + +/* Preserve data */ +preserve + +/* Check and open dataset */ +if ("`data'" == "") { + di as err "{p}Problem with option {bf:{ul:lin}e()}: suboption " /// + "{bf:{ul:d}ata()} is required{p_end}" + exit 198 +} +if (substr(reverse("`data'"),1,4) != "atd.") { + local data "`data'.dta" +} +capture confirm file "`data'" +if _rc { + di as err "{p}Problem with option {bf:{ul:lin}e()}: file " /// + "{bf:`data'} specified in suboption {bf:{ul:d}ata()} " /// + "not found{p_end}" + exit 601 +} +use "`data'", clear +cap confirm numeric variable _ID _X _Y +if _rc { + di as err "{p}Problem with option {bf:{ul:lin}e()}: file " /// + "{bf:`data'} specified in suboption {bf:{ul:d}ata()} " /// + "is not a valid {help spmap##sd_line:{it:line}} " /// + "dataset {p_end}" + exit 198 +} + +/* Select relevant records */ +if (`"`select'"' != "") { + cap `select' + if _rc { + di as err "{p}Problem with option {bf:{ul:lin}e()}: suboption " /// + "{bf:{ul:s}elect()} specified incorrectly{p_end}" + exit 198 + } +} + +/* Check option by() */ +if ("`by'" != "") { + cap unab by : `by' + if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:lin}e()}: " /// + "variable {bf:`by'} specified in suboption " /// + "{bf:{ul:by}()} not found{p_end}" + exit 111 + } + if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:lin}e()}: " /// + "string {bf:`by'} specified in suboption " /// + "{bf:{ul:by}()} is not a valid variable " /// + "name{p_end}" + exit 198 + } + local NW : word count `by' + if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:lin}e()}: " /// + "suboption {bf:{ul:by}()} accepts only one " /// + "variable{p_end}" + exit 198 + } +} + +/* Check option legenda() */ +if ("`legenda'" != "") { + local LIST "on off" + local EXIST : list posof "`legenda'" in LIST + if !`EXIST' { + di as err "{p}Problem with option {bf:{ul:lin}e()}: " /// + "suboption {bf:{ul:legenda}()} accepts only one " /// + "of the following keywords: {bf:`LIST'}{p_end}" + exit 198 + } +} + +/* Check options relevant only when legenda(on) */ +if ("`legenda'" == "on") { + + /* Check option leglabel() */ + if (`"`leglabel'"' == "") & ("`by'" == "") { + di as err "{p}Problem with option {bf:{ul:lin}e()}: since " /// + "you have specified suboption {bf:{ul:legenda}(on)} " /// + "but you have not specified any group variable in " /// + "suboption {bf:{ul:by}()}, you are requested to " /// + "specify suboption {bf:{ul:legl}abel()}{p_end}" + exit 198 + } + + /* Check option legshow() */ + if ("`legshow'" != "") { + cap numlist "`legshow'" + if _rc { + di as err "{p}Problem with option {bf:{ul:lin}e()}: " /// + "invalid numlist in suboption " /// + "{bf:{ul:legs}how()}{p_end}" + exit 121 + } + } + +/* End */ +} + +/* Marksample */ +marksample TOUSE +if ("`by'" != "") markout `TOUSE' `by', strok +qui count if `TOUSE' +if (r(N) == 0) error 2000 + + + + +* ---------------------------------------------------------------------------- +* 4. Define basic objects +* ---------------------------------------------------------------------------- + +/* Select relevant records */ +qui keep if `TOUSE' + +/* Set default line color */ +local color_d "black" +if (`"`color'"' == "") local color "`color_d' ..." + +/* Set default line thickness */ +local size_d "thin" +if ("`size'" == "") local size "`size_d' ..." + +/* Set default line pattern */ +local pattern_d "solid" +if (`"`pattern'"' == "") local pattern "`pattern_d' ..." + +/* Set default legend */ +if ("`legenda'" == "") local legenda "off" + +/* Set legend title when legtitle(varlab) */ +if ("`legenda'" == "on") & ("`by'" != "") & (`"`legtitle'"' == "varlab") { + local legtitle : variable label `by' + if (`"`legtitle'"' == "") local legtitle "`by'" +} + + + + +* ---------------------------------------------------------------------------- +* 5. Create working dataset +* ---------------------------------------------------------------------------- + +/* Housekeeping */ +cap drop __LIN* + +/* Generate group variable */ +if ("`by'" == "") qui gen __LIN_G = 1 +if ("`by'" != "") qui egen __LIN_G = group(`by'), lname(__LIN_G) +qui tab __LIN_G +local NG = r(r) + +/* Generate coordinate variables */ +qui gen __LIN_X = _X +qui gen __LIN_Y = _Y + +/* Count objects */ +if ("`legenda'" == "on") & ("`legcount'" != "") { + forval i = 1/`NG' { + qui tab _ID if __LIN_G == `i' + local COUNT "`COUNT'`r(r)' " + } +} + +/* Save dataset */ +keep __LIN* +qui save "__LIN.dta", replace + + + + +* ---------------------------------------------------------------------------- +* 6. Parse style lists +* ---------------------------------------------------------------------------- + +/* Set list of available color palettes */ +local PALETTE "`PALETTE' Accent Blues BrBG BuGn BuPu Dark2 GnBu Greens Greys" +local PALETTE "`PALETTE' OrRd Oranges PRGn Paired Pastel1 Pastel2 PiYG PuBu" +local PALETTE "`PALETTE' PuBuGn PuOr PuRd Purples RdBu RdGy RdPu RdYlBu" +local PALETTE "`PALETTE' RdYlGn Reds Set1 Set2 Set3 Spectral YlGn YlGnBu" +local PALETTE "`PALETTE' YlOrBr YlOrRd" +local PALETTE "`PALETTE' BuRd BuYlRd Heat Terrain Topological" +local PALETTE "`PALETTE' Blues2 Greens2 Greys2 Reds2 Rainbow" + +/* Parse option color() */ +local EXIST : list posof `"`color'"' in PALETTE +if `EXIST' { + if (`NG' > 1) { + spmap_color "`color'" `NG' + local color `"`s(colors)'"' + } + else { + di as err "{p}Problem with option {bf:{ul:lin}e()}: " /// + "when no group variable is specified in suboption " /// + "{bf:{ul:by}()}, suboption {bf:{ul:co}lor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`color') m(`NG') o({bf:{ul:co}lor()}) d(`color_d') + local color `"`s(pl)'"' +} + +/* Parse option size() */ +spmap_psl, l(`size') m(`NG') o({bf:{ul:si}ze()}) d(`size_d') +local size `"`s(pl)'"' + +/* Parse option pattern() */ +spmap_psl, l(`pattern') m(`NG') o({bf:{ul:pa}ttern()}) d(`pattern_d') +local pattern `"`s(pl)'"' + + + + +* ---------------------------------------------------------------------------- +* 7. Compose command +* ---------------------------------------------------------------------------- + +/* Compose command */ +forval i = 1/`NG' { + local COL : word `i' of `color' + local SIZ : word `i' of `size' + local PAT : word `i' of `pattern' + local GRAPH `"`GRAPH'(line __LIN_Y __LIN_X if __LIN_G == `i', nodropbase"' + local GRAPH `"`GRAPH' cmissing(n) lc("`COL'") lw("`SIZ'") lp("`PAT'")) "' +} + + + + +* ---------------------------------------------------------------------------- +* 8. Set legend order and labels +* ---------------------------------------------------------------------------- + +/* Set number of keys */ +local NK = `NG' + + +/* legenda(off) */ +if ("`legenda'" == "off") { + local TITLE "" + local KEY "" + local LABEL "" +} + + +/* legenda(on) & by == "" */ +if ("`legenda'" == "on") & ("`by'" == "") { + + /* Title */ + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + + /* Keys */ + local KEY "1 " + + /* Labels */ + if ("`legcount'" == "") { + local LABEL `"`"`leglabel'"' "' + } + else { + local OBS : word 1 of `COUNT' + local LABEL `"`"`leglabel' (`OBS')"' "' + } + +/* End */ +} + + +/* legenda(on) & by == !" */ +if ("`legenda'" == "on") & ("`by'" != "") { + + /* Title */ + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + + /* Keys */ + if ("`legshow'" == "") { + numlist "1/`NK'" + local KEY "`r(numlist)'" + } + else { + qui levelsof __LIN_G, local (VL) + local CHECK : list legshow in VL + if !`CHECK' { + di as err "{p}Problem with option {bf:{ul:lin}e()}: " /// + "one or more keys specified in suboption " /// + "{bf:{ul:legs}how()} do not exist. Valid keys " /// + " are: `VL'{p_end}" + exit 198 + } + else local KEY "`legshow'" + } + + /* Labels */ + foreach K in `KEY' { + local LBL : label (__LIN_G) `K' + if ("`legcount'" == "") { + local LABEL `"`LABEL'`"`LBL'"' "' + } + else { + local OBS : word `K' of `COUNT' + local LABEL `"`LABEL'`"`LBL' (`OBS')"' "' + } + } + +/* End */ +} + + + + +* ---------------------------------------------------------------------------- +* 9. Return info of interest +* ---------------------------------------------------------------------------- + +/* Return command */ +return local command `"`GRAPH'"' + +/* Return min/max coordinates */ +qui summ __LIN_X +return local xmin = r(min) +return local xmax = r(max) +qui summ __LIN_Y +return local ymin = r(min) +return local ymax = r(max) + +/* Return legend info */ +return local title `"`TITLE'"' +return local key `"`KEY'"' +return local label `"`LABEL'"' +return local nk = `NK' + + + + +* ---------------------------------------------------------------------------- +* 10. End program +* ---------------------------------------------------------------------------- + +restore +end + + + diff --git a/notebooks/msna/Codes/ado/s/spmap_point.ado b/notebooks/msna/Codes/ado/s/spmap_point.ado new file mode 100644 index 00000000..71b3eac9 --- /dev/null +++ b/notebooks/msna/Codes/ado/s/spmap_point.ado @@ -0,0 +1,955 @@ +*! -spmap_point-: Auxiliary program for -spmap- +*! Version 1.3.0 - 13 March 2017 +*! Version 1.2.0 - 14 March 2008 +*! Version 1.1.0 - 7 May 2007 +*! Version 1.0.0 - 7 December 2006 +*! Author: Maurizio Pisati +*! Department of Sociology and Social Research +*! University of Milano Bicocca (Italy) +*! maurizio.pisati@unimib.it + + + + +* ---------------------------------------------------------------------------- +* 1. Define program +* ---------------------------------------------------------------------------- + +program spmap_point, rclass +version 9.2 + + + + +* ---------------------------------------------------------------------------- +* 2. Define syntax +* ---------------------------------------------------------------------------- + +syntax, [Data(string)] /// + [Select(string asis)] /// + [BY(string)] /// + /// + [Xcoord(string)] /// + [Ycoord(string)] /// + /// + [PROPortional(string)] /// + [PRange(string)] /// + [PSize(string)] /// + /// + [DEViation(string)] /// + [DMax(string)] /// + [REFVal(string)] /// + [REFWeight(string)] /// + /// + [SIze(string)] /// 1.3.0 Bug fix + [SHape(string)] /// + [FColor(string asis)] /// + [OColor(string asis)] /// + [OSize(string)] /// + /// + [LEGENDA(string)] /// + [LEGTitle(string asis)] /// + [LEGLabel(string)] /// + [LEGShow(string)] /// + [LEGCount] + + + + +* ---------------------------------------------------------------------------- +* 3. Check syntax +* ---------------------------------------------------------------------------- + +/* Preserve data */ +preserve + +/* Check and open dataset */ +if ("`data'" != "") { + if (substr(reverse("`data'"),1,4) != "atd.") { + local data "`data'.dta" + } + capture confirm file "`data'" + if _rc { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: file " /// + "{bf:`data'} specified in suboption {bf:{ul:d}ata()} " /// + "not found{p_end}" + exit 601 + } + use "`data'", clear +} + +/* Select relevant records */ +if (`"`select'"' != "") { + cap `select' + if _rc { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: suboption " /// + "{bf:{ul:s}elect()} specified incorrectly{p_end}" + exit 198 + } +} + +/* Check option by() */ +if ("`by'" != "") { + cap unab by : `by' + if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "variable {bf:`by'} specified in suboption " /// + "{bf:{ul:by}()} not found{p_end}" + exit 111 + } + if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "string {bf:`by'} specified in suboption " /// + "{bf:{ul:by}()} is not a valid variable " /// + "name{p_end}" + exit 198 + } + local NW : word count `by' + if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:by}()} accepts only one " /// + "variable{p_end}" + exit 198 + } +} + +/* Check option xcoord() */ +if ("`xcoord'" == "") { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: suboption " /// + "{bf:{ul:x}coord()} is required{p_end}" + exit 198 +} +cap unab xcoord : `xcoord' +if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "variable {bf:`xcoord'} specified in suboption " /// + "{bf:{ul:x}coord()} not found{p_end}" + exit 111 +} +if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "string {bf:`xcoord'} specified in suboption " /// + "{bf:{ul:x}coord()} is not a valid variable " /// + "name{p_end}" + exit 198 +} +local NW : word count `xcoord' +if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:x}coord()} accepts only one " /// + "variable{p_end}" + exit 198 +} +cap confirm numeric variable `xcoord', exact +if _rc { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:x}coord()} accepts only " /// + "numeric variables{p_end}" + exit 7 +} + +/* Check option ycoord() */ +if ("`ycoord'" == "") { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: suboption " /// + "{bf:{ul:y}coord()} is required{p_end}" + exit 198 +} +cap unab ycoord : `ycoord' +if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "variable {bf:`ycoord'} specified in suboption " /// + "{bf:{ul:y}coord()} not found{p_end}" + exit 111 +} +if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "string {bf:`ycoord'} specified in suboption " /// + "{bf:{ul:y}coord()} is not a valid variable " /// + "name{p_end}" + exit 198 +} +local NW : word count `ycoord' +if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:y}coord()} accepts only one " /// + "variable{p_end}" + exit 198 +} +cap confirm numeric variable `ycoord', exact +if _rc { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:y}coord()} accepts only " /// + "numeric variables{p_end}" + exit 7 +} + +/* Check option proportional() */ +if ("`proportional'" != "") { + cap unab proportional : `proportional' + if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "variable {bf:`proportional'} specified in " /// + "suboption {bf:{ul:prop}ortional()} not " /// + "found{p_end}" + exit 111 + } + if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "string {bf:`proportional'} specified in " /// + "suboption {bf:{ul:prop}ortional()} is not " /// + "a valid variable name{p_end}" + exit 198 + } + local NW : word count `proportional' + if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:prop}ortional()} accepts " /// + "only one variable{p_end}" + exit 198 + } + cap confirm numeric variable `proportional', exact + if _rc { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:prop}ortional()} accepts " /// + "only numeric variables{p_end}" + exit 7 + } +} + +/* Check option prange() */ +if ("`prange'" != "") & ("`proportional'" != "") { + local NW : word count `prange' + if (`NW' != 2) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:pr}ange()} requires exactly " /// + "2 arguments{p_end}" + exit 198 + } + foreach W in `prange' { + cap confirm number `W' + if _rc { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:pr}ange()} accepts only " /// + "numbers{p_end}" + exit 7 + } + } + local N1 : word 1 of `prange' + local N2 : word 2 of `prange' + if (`N1' == `N2') { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "the two numbers specified in suboption " /// + "{bf:{ul:pr}ange()} must be different{p_end}" + exit 198 + } + local MIN = min(`N1', `N2') + local MAX = max(`N1', `N2') + local prange "`MIN' `MAX'" +} + +/* Check option psize() */ +if ("`psize'" != "") & ("`proportional'" != "") { + local LIST "absolute relative" + local EXIST : list posof "`psize'" in LIST + if !`EXIST' { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: suboption " /// + "{bf:{ul:ps}ize()} accepts only one of the following " /// + "keywords: {bf:`LIST'}{p_end}" + exit 198 + } +} + +/* Check option deviation() */ +if ("`deviation'" != "") { + if ("`proportional'" != "") { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: suboptions " /// + "{bf:{ul:prop}ortional()} and {bf:{ul:dev}iation()} " /// + "cannot be specified together{p_end}" + exit 198 + } + cap unab deviation : `deviation' + if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "variable {bf:`deviation'} specified in " /// + "suboption {bf:{ul:dev}iation()} not " /// + "found{p_end}" + exit 111 + } + if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "string {bf:`deviation'} specified in " /// + "suboption {bf:{ul:dev}iation()} is not " /// + "a valid variable name{p_end}" + exit 198 + } + local NW : word count `deviation' + if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:dev}iation()} accepts " /// + "only one variable{p_end}" + exit 198 + } + cap confirm numeric variable `deviation', exact + if _rc { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:dev}iation()} accepts " /// + "only numeric variables{p_end}" + exit 7 + } +} + +/* Check option dmax() */ +if ("`deviation'" != "") & ("`dmax'" != "") { + local NW : word count `dmax' + if (`NW' != 1) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:dm}ax()} accepts only 1 " /// + "argument{p_end}" + exit 198 + } + cap confirm number `dmax' + if _rc { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "suboption {bf:{ul:dm}ax()} accepts only " /// + "numbers{p_end}" + exit 7 + } + if (`dmax' <= 0) { + di as err "{p}Problem with option {bf:{ul:dia}gram()}: " /// + "the argument of suboption {bf:{ul:dm}ax()} " /// + "must be >0{p_end}" + exit 198 + } +} + +/* Check option refval() */ +if ("`deviation'" != "") & ("`refval'" != "") { + cap confirm number `refval' + if _rc { + local LIST "mean median" + local EXIST : list posof "`refval'" in LIST + if !`EXIST' { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: suboption " /// + "{bf:{ul:refv}al()} accepts only numbers or one of " /// + "the following keywords: {bf:`LIST'}{p_end}" + exit 198 + } + } + else local RVTYPE "NUM" +} + +/* Check option refweight() */ +if ("`refweight'" != "") & ("`deviation'" != "") { + cap unab refweight : `refweight' + if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "variable {bf:`refweight'} specified in " /// + "suboption {bf:{ul:refw}eight()} not " /// + "found{p_end}" + exit 111 + } + if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "string {bf:`refweight'} specified in " /// + "suboption {bf:{ul:refw}eight()} is not " /// + "a valid variable name{p_end}" + exit 198 + } + local NW : word count `refweight' + if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:refw}eight()} accepts only " /// + "one variable{p_end}" + exit 198 + } + cap confirm numeric variable `refweight', exact + if _rc { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:refw}eight()} accepts " /// + "only numeric variables{p_end}" + exit 7 + } +} + +/* Check option shape() */ +if ("`shape'" != "") & ("`deviation'" != "") { + local LIST "O D T S o d t s" + local NL : word count `shape' + forval i = 1/`NL' { + local SHP : word `i' of `shape' + if (!inlist("`SHP'",".","=","..","...")) { + local EXIST : list posof "`SHP'" in LIST + if !`EXIST' { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: when " /// + "suboption {bf:{ul:dev}iation()} is specified, " /// + "suboption {bf:{ul:sh}ape()} accepts only solid " /// + "symbol styles written in short form: " /// + "{bf:`LIST'}{p_end}" + exit 198 + } + } + } +} + +/* Check option legenda() */ +if ("`legenda'" != "") { + local LIST "on off" + local EXIST : list posof "`legenda'" in LIST + if !`EXIST' { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "suboption {bf:{ul:legenda}()} accepts only one " /// + "of the following keywords: {bf:`LIST'}{p_end}" + exit 198 + } +} + +/* Check options relevant only when legenda(on) */ +if ("`legenda'" == "on") { + + /* Check option leglabel() */ + if (`"`leglabel'"' == "") & ("`by'" == "") { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: since " /// + "you have specified suboption {bf:{ul:legenda}(on)} " /// + "but you have not specified any group variable in " /// + "suboption {bf:{ul:by}()}, you are requested to " /// + "specify suboption {bf:{ul:legl}abel()}{p_end}" + exit 198 + } + + /* Check option legshow() */ + if ("`legshow'" != "") { + cap numlist "`legshow'" + if _rc { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "invalid numlist in suboption " /// + "{bf:{ul:legs}how()}{p_end}" + exit 121 + } + } + +/* End */ +} + +/* Marksample */ +marksample TOUSE +markout `TOUSE' `xcoord' `ycoord' +if ("`by'" != "") markout `TOUSE' `by' +if ("`proportional'" != "") markout `TOUSE' `proportional' +if ("`deviation'" != "") markout `TOUSE' `deviation' +if ("`refweight'" != "" & "`deviation'" != "") markout `TOUSE' `refweight' +qui count if `TOUSE' +if (r(N) == 0) error 2000 + + + + +* ---------------------------------------------------------------------------- +* 4. Define basic objects +* ---------------------------------------------------------------------------- + +/* Select relevant observations */ +qui keep if `TOUSE' + + +/* Set defaults relevant only when proportional != "" */ +if ("`proportional'" != "") { + + /* Set default range for weighting variable normalization */ + if ("`prange'" == "") { + qui su `proportional', meanonly + local prange "0 `r(max)'" + } + + /* Set min-max values for weighting variable normalization */ + local PMIN : word 1 of `prange' + local PMAX : word 2 of `prange' + + /* Set default reference system for weighting */ + if ("`psize'" == "") local psize "relative" + +/* End */ +} + + +/* Set defaults relevant only when deviation != "" */ +if ("`deviation'" != "") { + + /* Set default reference value */ + if ("`refval'" == "") local refval "mean" + + /* Set STAT corresponding to specified reference value */ + if ("`refval'" == "mean") local STAT "mean" + if ("`refval'" == "median") local STAT "p50" + + /* Set reference weight */ + if ("`refweight'" != "") local REFWEIGHT "[aweight = `refweight']" + +/* End */ +} + + +/* Set default symbol size */ +local size_d "*1" +if ("`size'" == "") local size "`size_d' ..." + +/* Set default symbol shape */ +local shape_d "o" +if ("`shape'" == "") local shape "`shape_d' ..." + +/* Set default symbol fill color */ +local fcolor_d "black" +if (`"`fcolor'"' == "") local fcolor "`fcolor_d' ..." + +/* Set default outline color */ +local ocolor_d "none" +if (`"`ocolor'"' == "") local ocolor "`ocolor_d' ..." + +/* Set default outline thickness */ +local osize_d "thin" +if ("`osize'" == "") local osize "`osize_d' ..." + + +/* Set default legend */ +if ("`legenda'" == "") local legenda "off" + +/* Set legend title when legtitle(varlab) */ +if ("`legenda'" == "on") & ("`by'" != "") & (`"`legtitle'"' == "varlab") { + local legtitle : variable label `by' + if (`"`legtitle'"' == "") local legtitle "`by'" +} + + + + +* ---------------------------------------------------------------------------- +* 5. Create working dataset +* ---------------------------------------------------------------------------- + +/* Housekeeping */ +cap drop __POI* + +/* Generate weighting variable */ +if ("`proportional'" == "") qui gen __POI_W = 1 +if ("`proportional'" != "") { + qui gen __POI_W = (`proportional' - `PMIN') / (`PMAX' - `PMIN') + gsort -__POI_W +} + +/* Generate sign and weighting variables if deviation != "" */ +if ("`deviation'" != "") { + if ("`RVTYPE'" == "NUM") local RV = `refval' + else { + qui su `deviation' `REFWEIGHT', detail + local RV = r(`STAT') + } + qui gen __POI_S = sign(`deviation' - `RV') + qui recode __POI_S (0=1) + qui replace __POI_W = abs(`deviation' - `RV') + gsort -__POI_S -__POI_W +} + +/* Generate group variable */ +if ("`by'" == "") qui gen __POI_G = 1 +if ("`by'" != "") qui egen __POI_G = group(`by'), lname(__POI_G) +qui tab __POI_G +local NG = r(r) + +/* Generate dummy cases */ +qui count +local NOBS = r(N) +if ("`proportional'" != "") { + local NOBS2 = `NOBS' + `NG' * 2 + qui set obs `NOBS2' + if ("`psize'" == "absolute") { + local WMIN = 0 + local WMAX = 1 + } + else { + qui su __POI_W + local WMIN = r(min) + local WMAX = r(max) + } + local ROW = `NOBS' + 1 + forval i = 1/`NG' { + qui replace __POI_G = `i' in `ROW' + qui replace __POI_W = `WMIN' in `ROW' + local ROW = `ROW' + 1 + qui replace __POI_G = `i' in `ROW' + qui replace __POI_W = `WMAX' in `ROW' + local ROW = `ROW' + 1 + } + gsort __POI_G -__POI_W +} +if ("`deviation'" != "") { + local NOBS2 = `NOBS' + `NG' * 2 * 2 + qui set obs `NOBS2' + if ("`dmax'" != "") local WMAX = `dmax' + else { + qui su __POI_W + local WMAX = r(max) + } + local ROW = `NOBS' + 1 + forval i = 1/`NG' { + qui replace __POI_G = `i' in `ROW' + qui replace __POI_S = -1 in `ROW' + qui replace __POI_W = 0 in `ROW' + local ROW = `ROW' + 1 + qui replace __POI_G = `i' in `ROW' + qui replace __POI_S = -1 in `ROW' + qui replace __POI_W = `WMAX' in `ROW' + local ROW = `ROW' + 1 + qui replace __POI_G = `i' in `ROW' + qui replace __POI_S = 1 in `ROW' + qui replace __POI_W = 0 in `ROW' + local ROW = `ROW' + 1 + qui replace __POI_G = `i' in `ROW' + qui replace __POI_S = 1 in `ROW' + qui replace __POI_W = `WMAX' in `ROW' + local ROW = `ROW' + 1 + } + gsort -__POI_S __POI_G -__POI_W +} + +/* Generate coordinate variables */ +qui gen __POI_X = `xcoord' +qui gen __POI_Y = `ycoord' + +/* Set number of keys */ +if ("`deviation'" == "") local NK = `NG' +else local NK = `NG' * 2 + +/* Count points */ +if ("`legenda'" == "on") & ("`legcount'" != "") { + if ("`deviation'" == "") { + forval i = 1/`NG' { + qui count if __POI_G == `i' & __POI_X != . + if (r(N) > 0) local COUNT "`COUNT'`r(N)' " + } + } + else { + forval j = 1(-2)-1 { + forval i = 1/`NG' { + qui count if __POI_S == `j' & __POI_G == `i' & __POI_X != . + if (r(N) > 0) local COUNT "`COUNT'`r(N)' " + } + } + } +} + +/* Save dataset */ +keep __POI* +qui save "__POI.dta", replace + + + + +* ---------------------------------------------------------------------------- +* 6. Parse style lists +* ---------------------------------------------------------------------------- + +/* Set list of available color palettes */ +local PALETTE "`PALETTE' Accent Blues BrBG BuGn BuPu Dark2 GnBu Greens Greys" +local PALETTE "`PALETTE' OrRd Oranges PRGn Paired Pastel1 Pastel2 PiYG PuBu" +local PALETTE "`PALETTE' PuBuGn PuOr PuRd Purples RdBu RdGy RdPu RdYlBu" +local PALETTE "`PALETTE' RdYlGn Reds Set1 Set2 Set3 Spectral YlGn YlGnBu" +local PALETTE "`PALETTE' YlOrBr YlOrRd" +local PALETTE "`PALETTE' BuRd BuYlRd Heat Terrain Topological" +local PALETTE "`PALETTE' Blues2 Greens2 Greys2 Reds2 Rainbow" + +/* Parse option size() */ +spmap_psl, l(`size') m(`NG') o({bf:{ul:si}ze()}) d(`size_d') +local size `"`s(pl)'"' + +/* Parse option shape() */ +spmap_psl, l(`shape') m(`NG') o({bf:{ul:sh}ape()}) d(`shape_d') +local shape `"`s(pl)'"' + +/* Parse option fcolor() */ +local EXIST : list posof `"`fcolor'"' in PALETTE +if `EXIST' { + if (`NG' > 1) { + spmap_color "`fcolor'" `NG' + local fcolor `"`s(colors)'"' + } + else { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "when no group variable is specified in suboption " /// + "{bf:{ul:by}()}, suboption {bf:{ul:fc}olor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`fcolor') m(`NG') o({bf:{ul:fc}olor()}) d(`fcolor_d') + local fcolor `"`s(pl)'"' +} + +/* Parse option ocolor() */ +local EXIST : list posof `"`ocolor'"' in PALETTE +if `EXIST' { + if (`NG' > 1) { + spmap_color "`ocolor'" `NG' + local ocolor `"`s(colors)'"' + } + else { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "when no group variable is specified in suboption " /// + "{bf:{ul:by}()}, suboption {bf:{ul:oc}olor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`ocolor') m(`NG') o({bf:{ul:oc}olor()}) d(`ocolor_d') + local ocolor `"`s(pl)'"' +} + +/* Parse option osize() */ +spmap_psl, l(`osize') m(`NG') o({bf:{ul:os}ize()}) d(`osize_d') +local osize `"`s(pl)'"' + + + + +* ---------------------------------------------------------------------------- +* 7. Compose command +* ---------------------------------------------------------------------------- + +/* Compose command */ +if ("`proportional'" != "") { + forval i = 1/`NG' { + local SI : word 1 of `size' + local SH : word `i' of `shape' + local FC : word `i' of `fcolor' + local OC : word `i' of `ocolor' + if ("`OC'" == "none") local OC "`FC'" + local OS : word `i' of `osize' + local GRAPH `"`GRAPH'(scatter __POI_Y __POI_X [aw = __POI_W]"' + local GRAPH `"`GRAPH' if __POI_G == `i', ms("`SH'") mc("`FC'")"' + local GRAPH `"`GRAPH' msize("`SI'") mlw("`OS'") mlc("`OC'") ) "' + } +} + +if ("`deviation'" != "") { + forval i = 1/`NG' { + local SI : word 1 of `size' + local SH : word `i' of `shape' + local FC : word `i' of `fcolor' + local OC : word `i' of `ocolor' + if ("`OC'" == "none") local OC "`FC'" + local OS : word `i' of `osize' + local GRAPH `"`GRAPH'(scatter __POI_Y __POI_X [aw = __POI_W]"' + local GRAPH `"`GRAPH' if __POI_G == `i' & __POI_S == 1,"' + local GRAPH `"`GRAPH' ms("`SH'") mc("`FC'") msize("`SI'")"' + local GRAPH `"`GRAPH' mlw("`OS'") mlc("`OC'") ) "' + } + forval i = 1/`NG' { + local SI : word 1 of `size' + local SH : word `i' of `shape' + local FC "none" + local OC : word `i' of `fcolor' + local OS : word `i' of `osize' + local GRAPH `"`GRAPH'(scatter __POI_Y __POI_X [aw = __POI_W]"' + local GRAPH `"`GRAPH' if __POI_G == `i' & __POI_S == -1,"' + local GRAPH `"`GRAPH' ms("`SH'h") mc("`FC'") msize("`SI'")"' + local GRAPH `"`GRAPH' mlw("`OS'") mlc("`OC'") ) "' + } +} + +if ("`proportional'" == "") & ("`deviation'" == "") { + forval i = 1/`NG' { + local SI : word `i' of `size' + local SH : word `i' of `shape' + local FC : word `i' of `fcolor' + local OC : word `i' of `ocolor' + if ("`OC'" == "none") local OC "`FC'" + local OS : word `i' of `osize' + local GRAPH `"`GRAPH'(scatter __POI_Y __POI_X [aw = __POI_W]"' + local GRAPH `"`GRAPH' if __POI_G == `i', ms("`SH'") mc("`FC'")"' + local GRAPH `"`GRAPH' msize("`SI'") mlw("`OS'") mlc("`OC'") ) "' + } +} + + + + +* ---------------------------------------------------------------------------- +* 8. Set legend order and labels +* ---------------------------------------------------------------------------- + +/* legenda(off) */ +if ("`legenda'" == "off") { + local TITLE "" + local KEY "" + local LABEL "" +} + + +/* legenda(on) & by == "" & deviation == "" */ +if ("`legenda'" == "on") & ("`by'" == "") & ("`deviation'" == "") { + + /* Title */ + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + + /* Keys */ + local KEY "1 " + + /* Labels */ + if ("`legcount'" == "") { + local LABEL `"`"`leglabel'"' "' + } + else { + local OBS : word 1 of `COUNT' + local LABEL `"`"`leglabel' (`OBS')"' "' + } + +/* End */ +} + + +/* legenda(on) & by != "" & deviation == "" */ +if ("`legenda'" == "on") & ("`by'" != "") & ("`deviation'" == "") { + + /* Title */ + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + + /* Keys */ + numlist "1/`NK'" + local KEY "`r(numlist)'" + if ("`legshow'" != "") { + local CHECK : list legshow in KEY + if !`CHECK' { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "one or more keys specified in suboption " /// + "{bf:{ul:legs}how()} do not exist. Valid keys " /// + " are: `KEY'{p_end}" + exit 198 + } + else local KEY "`legshow'" + } + + /* Labels */ + foreach K in `KEY' { + local LBL : label (__POI_G) `K' + if ("`legcount'" == "") { + local LABEL `"`LABEL'`"`LBL'"' "' + } + else { + local OBS : word `K' of `COUNT' + local LABEL `"`LABEL'`"`LBL' (`OBS')"' "' + } + } + +/* End */ +} + + +/* legenda(on) & deviation != "" */ +if ("`legenda'" == "on") & ("`deviation'" != "") { + + /* Title */ + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + + /* Keys */ + local K = 1 + forval j = 1(-2)-1 { + forval i = 1/`NG' { + qui count if __POI_S == `j' & __POI_G == `i' & __POI_X != . + if (r(N) > 0) { + local KEY "`KEY'`K' " + local VAL "`VAL'`i' " + local SGN "`SGN'`j' " + } + local K = `K' + 1 + } + } + if ("`legshow'" != "") { + local CHECK : list legshow in KEY + if !`CHECK' { + di as err "{p}Problem with option {bf:{ul:poi}nt()}: " /// + "one or more keys specified in suboption " /// + "{bf:{ul:legs}how()} do not exist. Valid keys " /// + " are: `KEY'{p_end}" + exit 198 + } + else local KEY "`legshow'" + } + + /* Labels */ + local NW : word count `KEY' + forval i = 1/`NW' { + local V : word `i' of `VAL' + local S : word `i' of `SGN' + if ("`S'" == "1") local S "[+]" + if ("`S'" == "-1") local S "[-]" + if ("`by'" != "") local LBL : label (__POI_G) `V' + else local LBL `"`leglabel'"' + if ("`legcount'" == "") { + local LABEL `"`LABEL'`"`LBL'`S'"' "' + } + else { + local OBS : word `i' of `COUNT' + local LABEL `"`LABEL'`"`LBL'`S' (`OBS')"' "' + } + } + +/* End */ +} + + + + +* ---------------------------------------------------------------------------- +* 9. Return info of interest +* ---------------------------------------------------------------------------- + +/* Return command */ +return local command `"`GRAPH'"' + +/* Return min/max coordinates */ +qui summ __POI_X +return local xmin = r(min) +return local xmax = r(max) +qui summ __POI_Y +return local ymin = r(min) +return local ymax = r(max) + +/* Return legend info */ +return local title `"`TITLE'"' +return local key `"`KEY'"' +return local label `"`LABEL'"' +return local nk = `NK' + + + + +* ---------------------------------------------------------------------------- +* 10. End program +* ---------------------------------------------------------------------------- + +restore +end + + + diff --git a/notebooks/msna/Codes/ado/s/spmap_polygon.ado b/notebooks/msna/Codes/ado/s/spmap_polygon.ado new file mode 100644 index 00000000..5d2989ac --- /dev/null +++ b/notebooks/msna/Codes/ado/s/spmap_polygon.ado @@ -0,0 +1,452 @@ +*! -spmap_polygon-: Auxiliary program for -spmap- +*! Version 1.3.1 - 09 January 2018 - StataCorp edit for stroke align +*! Version 1.3.0 - 13 March 2017 +*! Version 1.2.0 - 14 March 2008 +*! Version 1.1.0 - 7 May 2007 +*! Version 1.0.0 - 7 December 2006 +*! Author: Maurizio Pisati +*! Department of Sociology and Social Research +*! University of Milano Bicocca (Italy) +*! maurizio.pisati@unimib.it + + + + +* ---------------------------------------------------------------------------- +* 1. Define program +* ---------------------------------------------------------------------------- + +program spmap_polygon, rclass +version 9.2 + + + + +* ---------------------------------------------------------------------------- +* 2. Define syntax +* ---------------------------------------------------------------------------- + +syntax, [Data(string)] /// + [Select(string asis)] /// + [BY(string)] /// + /// + [FColor(string asis)] /// + [OColor(string asis)] /// + [OSize(string)] /// + [OPattern(string)] /// 1.3.0 + [OAlign(string)] /// + /// + [LEGENDA(string)] /// + [LEGTitle(string asis)] /// + [LEGLabel(string)] /// + [LEGShow(string)] /// + [LEGCount] + + + + +* ---------------------------------------------------------------------------- +* 3. Check syntax +* ---------------------------------------------------------------------------- + +/* Preserve data */ +preserve + +/* Check and open dataset */ +if ("`data'" == "") { + di as err "{p}Problem with option {bf:{ul:pol}ygon()}: suboption " /// + "{bf:{ul:d}ata()} is required{p_end}" + exit 198 +} +if (substr(reverse("`data'"),1,4) != "atd.") { + local data "`data'.dta" +} +capture confirm file "`data'" +if _rc { + di as err "{p}Problem with option {bf:{ul:pol}ygon()}: file " /// + "{bf:`data'} specified in suboption {bf:{ul:d}ata()} " /// + "not found{p_end}" + exit 601 +} +use "`data'", clear +cap confirm numeric variable _ID _X _Y +if _rc { + di as err "{p}Problem with option {bf:{ul:pol}ygon()}: file " /// + "{bf:`data'} specified in suboption {bf:{ul:d}ata()} " /// + "is not a valid {help spmap##sd_polygon:{it:polygon}} " /// + "dataset {p_end}" + exit 198 +} + +/* Select relevant records */ +if (`"`select'"' != "") { + cap `select' + if _rc { + di as err "{p}Problem with option {bf:{ul:pol}ygon()}: suboption " /// + "{bf:{ul:s}elect()} specified incorrectly{p_end}" + exit 198 + } +} + +/* Check option by() */ +if ("`by'" != "") { + cap unab by : `by' + if (_rc == 111) { + di as err "{p}Problem with option {bf:{ul:pol}ygon()}: " /// + "variable {bf:`by'} specified in suboption " /// + "{bf:{ul:by}()} not found{p_end}" + exit 111 + } + if (_rc == 198) { + di as err "{p}Problem with option {bf:{ul:pol}ygon()}: " /// + "string {bf:`by'} specified in suboption " /// + "{bf:{ul:by}()} is not a valid variable " /// + "name{p_end}" + exit 198 + } + local NW : word count `by' + if (`NW' > 1) { + di as err "{p}Problem with option {bf:{ul:pol}ygon()}: " /// + "suboption {bf:{ul:by}()} accepts only one " /// + "variable{p_end}" + exit 198 + } +} + +/* Check option legenda() */ +if ("`legenda'" != "") { + local LIST "on off" + local EXIST : list posof "`legenda'" in LIST + if !`EXIST' { + di as err "{p}Problem with option {bf:{ul:pol}ygon()}: " /// + "suboption {bf:{ul:legenda}()} accepts only one " /// + "of the following keywords: {bf:`LIST'}{p_end}" + exit 198 + } +} + +/* Check options relevant only when legenda(on) */ +if ("`legenda'" == "on") { + + /* Check option leglabel() */ + if (`"`leglabel'"' == "") & ("`by'" == "") { + di as err "{p}Problem with option {bf:{ul:pol}ygon()}: since " /// + "you have specified suboption {bf:{ul:legenda}(on)} " /// + "but you have not specified any group variable in " /// + "suboption {bf:{ul:by}()}, you are requested to " /// + "specify suboption {bf:{ul:legl}abel()}{p_end}" + exit 198 + } + + /* Check option legshow() */ + if ("`legshow'" != "") { + cap numlist "`legshow'" + if _rc { + di as err "{p}Problem with option {bf:{ul:pol}ygon()}: " /// + "invalid numlist in suboption " /// + "{bf:{ul:legs}how()}{p_end}" + exit 121 + } + } + +/* End */ +} + +/* Marksample */ +marksample TOUSE +if ("`by'" != "") markout `TOUSE' `by', strok +qui count if `TOUSE' +if (r(N) == 0) error 2000 + + + + +* ---------------------------------------------------------------------------- +* 4. Define basic objects +* ---------------------------------------------------------------------------- + +/* Select relevant records */ +qui keep if `TOUSE' + +/* Set default fill color */ +local fcolor_d "none" +if (`"`fcolor'"' == "") local fcolor "`fcolor_d' ..." + +/* Set default outline color */ +local ocolor_d "black" +if (`"`ocolor'"' == "") local ocolor "`ocolor_d' ..." + +/* Set default outline thickness */ +local osize_d "thin" +if ("`osize'" == "") local osize "`osize_d' ..." + +/* Set default outline pattern */ +local opattern_d "solid" +if ("`opattern'" == "") local opattern "`opattern_d' ..." + +/* Set default outline alignment */ +local oalign_d "center" +if ("`oalign'" == "") local oalign "`oalign_d' ..." + +/* Set default legend */ +if ("`legenda'" == "") local legenda "off" + +/* Set legend title when legtitle(varlab) */ +if ("`legenda'" == "on") & ("`by'" != "") & (`"`legtitle'"' == "varlab") { + local legtitle : variable label `by' + if (`"`legtitle'"' == "") local legtitle "`by'" +} + + + + +* ---------------------------------------------------------------------------- +* 5. Create working dataset +* ---------------------------------------------------------------------------- + +/* Housekeeping */ +cap drop __POL* + +/* Generate group variable */ +if ("`by'" == "") qui gen __POL_G = 1 +if ("`by'" != "") qui egen __POL_G = group(`by'), lname(__POL_G) +qui tab __POL_G +local NG = r(r) + +/* Generate coordinate variables */ +qui gen __POL_X = _X +qui gen __POL_Y = _Y + +/* Count objects */ +if ("`legenda'" == "on") & ("`legcount'" != "") { + forval i = 1/`NG' { + qui tab _ID if __POL_G == `i' + local COUNT "`COUNT'`r(r)' " + } +} + +/* Save dataset */ +keep __POL* +qui save "__POL.dta", replace + + + + +* ---------------------------------------------------------------------------- +* 6. Parse style lists +* ---------------------------------------------------------------------------- + +/* Set list of available color palettes */ +local PALETTE "`PALETTE' Accent Blues BrBG BuGn BuPu Dark2 GnBu Greens Greys" +local PALETTE "`PALETTE' OrRd Oranges PRGn Paired Pastel1 Pastel2 PiYG PuBu" +local PALETTE "`PALETTE' PuBuGn PuOr PuRd Purples RdBu RdGy RdPu RdYlBu" +local PALETTE "`PALETTE' RdYlGn Reds Set1 Set2 Set3 Spectral YlGn YlGnBu" +local PALETTE "`PALETTE' YlOrBr YlOrRd" +local PALETTE "`PALETTE' BuRd BuYlRd Heat Terrain Topological" +local PALETTE "`PALETTE' Blues2 Greens2 Greys2 Reds2 Rainbow" + +/* Parse option fcolor() */ +local EXIST : list posof `"`fcolor'"' in PALETTE +if `EXIST' { + if (`NG' > 1) { + spmap_color "`fcolor'" `NG' + local fcolor `"`s(colors)'"' + } + else { + di as err "{p}Problem with option {bf:{ul:pol}ygon()}: " /// + "when no group variable is specified in suboption " /// + "{bf:{ul:by}()}, suboption {bf:{ul:fc}olor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`fcolor') m(`NG') o({bf:{ul:fc}olor()}) d(`fcolor_d') + local fcolor `"`s(pl)'"' +} + +/* Parse option ocolor() */ +local EXIST : list posof `"`ocolor'"' in PALETTE +if `EXIST' { + if (`NG' > 1) { + spmap_color "`ocolor'" `NG' + local ocolor `"`s(colors)'"' + } + else { + di as err "{p}Problem with option {bf:{ul:pol}ygon()}: " /// + "when no group variable is specified in suboption " /// + "{bf:{ul:by}()}, suboption {bf:{ul:oc}olor()} " /// + "does not accept palette names{p_end}" + exit 198 + } +} +else { + spmap_psl, l(`ocolor') m(`NG') o({bf:{ul:oc}olor()}) d(`ocolor_d') + local ocolor `"`s(pl)'"' +} + +/* Parse option osize() */ +spmap_psl, l(`osize') m(`NG') o({bf:{ul:os}ize()}) d(`osize_d') +local osize `"`s(pl)'"' + +/* Parse option opattern() */ +spmap_psl, l(`opattern') m(`NG') o({bf:{ul:op}attern()}) d(`opattern_d') +local opattern `"`s(pl)'"' + +/* Parse option oalign() */ +spmap_psl, l(`oalign') m(`NG') o({bf:{ul:op}attern()}) d(`oalign_d') +local oalign `"`s(pl)'"' + + + + +* ---------------------------------------------------------------------------- +* 7. Compose command +* ---------------------------------------------------------------------------- + +/* Compose command */ +forval i = 1/`NG' { + local FC : word `i' of `fcolor' + local OC : word `i' of `ocolor' + if ("`OC'" == "none") local OC "`FC'" + local OS : word `i' of `osize' + local OP : word `i' of `opattern' + local OA : word `i' of `oalign' + if c(stata_version) >= 15 { + local LA `"la("`OA'")"' + } + local GRAPH `"`GRAPH'(area __POL_Y __POL_X if __POL_G == `i', nodropbase"' + local GRAPH `"`GRAPH' cmissing(n) fc("`FC'") fi(100) lc("`OC'")"' + local GRAPH `"`GRAPH' lw("`OS'") lp("`OP'") `LA') "' +} + + + + +* ---------------------------------------------------------------------------- +* 8. Set legend order and labels +* ---------------------------------------------------------------------------- + +/* Set number of keys */ +local NK = `NG' + + +/* legenda(off) */ +if ("`legenda'" == "off") { + local TITLE "" + local KEY "" + local LABEL "" +} + + +/* legenda(on) & by == "" */ +if ("`legenda'" == "on") & ("`by'" == "") { + + /* Title */ + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + + /* Keys */ + local KEY "1 " + + /* Labels */ + if ("`legcount'" == "") { + local LABEL `"`"`leglabel'"' "' + } + else { + local OBS : word 1 of `COUNT' + local LABEL `"`"`leglabel' (`OBS')"' "' + } + +/* End */ +} + + +/* legenda(on) & by == !" */ +if ("`legenda'" == "on") & ("`by'" != "") { + + /* Title */ + if (`"`legtitle'"' != "") { + local Q = strpos(`"`legtitle'"',`"""') /* " */ + if (`Q' == 0) local TITLE `"- "`legtitle'""' + else local TITLE `"- `legtitle'"' + } + else { + local TITLE "" + } + + /* Keys */ + if ("`legshow'" == "") { + numlist "1/`NK'" + local KEY "`r(numlist)'" + } + else { + qui levelsof __POL_G, local (VL) + local CHECK : list legshow in VL + if !`CHECK' { + di as err "{p}Problem with option {bf:{ul:pol}ygon()}: " /// + "one or more keys specified in suboption " /// + "{bf:{ul:legs}how()} do not exist. Valid keys " /// + " are: `VL'{p_end}" + exit 198 + } + else local KEY "`legshow'" + } + + /* Labels */ + foreach K in `KEY' { + local LBL : label (__POL_G) `K' + if ("`legcount'" == "") { + local LABEL `"`LABEL'`"`LBL'"' "' + } + else { + local OBS : word `K' of `COUNT' + local LABEL `"`LABEL'`"`LBL' (`OBS')"' "' + } + } + +/* End */ +} + + + + +* ---------------------------------------------------------------------------- +* 9. Return info of interest +* ---------------------------------------------------------------------------- + +/* Return command */ +return local command `"`GRAPH'"' + +/* Return min/max coordinates */ +qui summ __POL_X +return local xmin = r(min) +return local xmax = r(max) +qui summ __POL_Y +return local ymin = r(min) +return local ymax = r(max) + +/* Return legend info */ +return local title `"`TITLE'"' +return local key `"`KEY'"' +return local label `"`LABEL'"' +return local nk = `NK' + + + + +* ---------------------------------------------------------------------------- +* 10. End program +* ---------------------------------------------------------------------------- + +restore +end + + + diff --git a/notebooks/msna/Codes/ado/s/spmap_psl.ado b/notebooks/msna/Codes/ado/s/spmap_psl.ado new file mode 100644 index 00000000..44cf23a7 --- /dev/null +++ b/notebooks/msna/Codes/ado/s/spmap_psl.ado @@ -0,0 +1,98 @@ +*! -spmap_psl-: Auxiliary program for -spmap- +*! Version 1.3.0 - 13 March 2017 +*! Version 1.2.0 - 14 March 2008 +*! Version 1.1.0 - 7 May 2007 +*! Version 1.0.0 - 7 December 2006 +*! Author: Maurizio Pisati +*! Department of Sociology and Social Research +*! University of Milano Bicocca (Italy) +*! maurizio.pisati@unimib.it + + + + +* ---------------------------------------------------------------------------- +* 1. Define program +* ---------------------------------------------------------------------------- + +program spmap_psl, sclass +version 9.2 + + + + +* ---------------------------------------------------------------------------- +* 2. Define syntax +* ---------------------------------------------------------------------------- + +syntax, List(string asis) Max(numlist min=1 max=1 >0 integer) /// + Option(string asis) [Default(string)] + + + + +* ---------------------------------------------------------------------------- +* 3. Parse list +* ---------------------------------------------------------------------------- + +local FIRST : word 1 of `list' +if (inlist("`FIRST'","=","..","...")) { + di as err `"{p}Option `option' does not accept symbol "`FIRST'" "' /// + "as its first argument{p_end}" + exit 198 +} +local NL : word count `list' +forval i = 1/`NL' { + local ITEM : word `i' of `list' + if ("`ITEM'" == ".") { + if ("`default'" != "") { + local EL "`default'" + local PL `"`PL'"`EL'" "' + } + else { + di as err `"{p}Option `option' does not accept symbol ".", "' /// + `"since no default value exists for this "' /// + `"option{p_end}"' + exit 198 + } + } + else if ("`ITEM'" == "=") { + local EL `"`: word `=`i'-1' of `PL''"' + local PL `"`PL'"`EL'" "' + } + else if ("`ITEM'" == ".." | "`ITEM'" == "...") { + local EL `"`: word `=`i'-1' of `PL''"' + forval j = `i'/`max' { + local PL `"`PL'"`EL'" "' + } + continue, break + } + else { + local PL `"`PL'"`ITEM'" "' + } +} +local NL : word count `PL' +if (`NL' < `max') { + if ("`default'" != "") { + forval i = `=`NL'+1'/`max' { + local PL `"`PL'"`default'" "' + } + } + else { + di as err "{p}Option `option' requires exactly `max' arguments{p_end}" + exit 198 + } +} +sreturn local pl `"`PL'"' + + + + +* ---------------------------------------------------------------------------- +* 4. End program +* ---------------------------------------------------------------------------- + +end + + + diff --git a/notebooks/msna/Codes/ado/s/spmap_scalebar.ado b/notebooks/msna/Codes/ado/s/spmap_scalebar.ado new file mode 100644 index 00000000..b5dccb32 --- /dev/null +++ b/notebooks/msna/Codes/ado/s/spmap_scalebar.ado @@ -0,0 +1,305 @@ +*! -spmap_scalebar-: Auxiliary program for -spmap- +*! Version 1.3.1 - 09 January 2018 - StataCorp edit for stroke align +*! Version 1.3.0 - 13 March 2017 +*! Version 1.2.0 - 14 March 2008 +*! Version 1.1.0 - 7 May 2007 +*! Version 1.0.0 - 7 December 2006 +*! Author: Maurizio Pisati +*! Department of Sociology and Social Research +*! University of Milano Bicocca (Italy) +*! maurizio.pisati@unimib.it + + + + +* ---------------------------------------------------------------------------- +* 1. Define program +* ---------------------------------------------------------------------------- + +program spmap_scalebar, rclass +version 9.2 + + + + +* ---------------------------------------------------------------------------- +* 2. Define syntax +* ---------------------------------------------------------------------------- + +syntax, [Units(string)] /// + [Scale(string)] /// + [Xpos(string)] /// + [Ypos(string)] /// + /// + [SIze(string)] /// + [FColor(string asis)] /// + [OColor(string asis)] /// + [OSize(string)] /// + [OAlign(string)] /// + [LAbel(string)] /// + [TColor(string asis)] /// + [TSize(string)] /// + [TAlign(string)] /// + /// + XMIN(string) /// + XMAX(string) /// + YMIN(string) /// + YMAX(string) + + + + +* ---------------------------------------------------------------------------- +* 3. Check syntax +* ---------------------------------------------------------------------------- + +/* Check option units() */ +if ("`units'" == "") { + di as err "{p}Problem with option {bf:{ul:sca}lebar()}: suboption " /// + "{bf:{ul:u}nits()} is required{p_end}" + exit 198 +} +cap confirm number `units' +if _rc { + di as err "{p}Problem with option {bf:{ul:sca}lebar()}: " /// + "suboption {bf:{ul:u}nits()} accepts only " /// + "numbers{p_end}" + exit 7 +} +if (`units' <= 0) { + di as err "{p}Problem with option {bf:{ul:sca}lebar()}: " /// + "suboption {bf:{ul:u}nits()} accepts only " /// + "positive numbers{p_end}" + exit 198 +} + +/* Check option scale() */ +if ("`scale'" != "") { + local scale = `scale' + cap confirm number `scale' + if _rc { + di as err "{p}Problem with option {bf:{ul:sca}lebar()}: " /// + "suboption {bf:{ul:s}cale()} accepts only " /// + "numbers{p_end}" + exit 7 + } + if (`scale' <= 0) { + di as err "{p}Problem with option {bf:{ul:sca}lebar()}: " /// + "suboption {bf:{ul:s}cale()} accepts only " /// + "positive numbers{p_end}" + exit 198 + } +} + +/* Check option xpos() */ +if ("`xpos'" != "") { + cap confirm number `xpos' + if _rc { + di as err "{p}Problem with option {bf:{ul:sca}lebar()}: " /// + "suboption {bf:{ul:x}pos()} accepts only " /// + "numbers{p_end}" + exit 7 + } +} + +/* Check option ypos() */ +if ("`ypos'" != "") { + cap confirm number `ypos' + if _rc { + di as err "{p}Problem with option {bf:{ul:sca}lebar()}: " /// + "suboption {bf:{ul:y}pos()} accepts only " /// + "numbers{p_end}" + exit 7 + } +} + +/* Check option size() */ +if ("`size'" != "") { + cap confirm number `size' + if _rc { + di as err "{p}Problem with option {bf:{ul:sca}lebar()}: " /// + "suboption {bf:{ul:si}ze()} accepts only " /// + "numbers{p_end}" + exit 7 + } + if (`size' <= 0) { + di as err "{p}Problem with option {bf:{ul:sca}lebar()}: " /// + "suboption {bf:{ul:si}ze()} accepts only " /// + "positive numbers{p_end}" + exit 198 + } +} + + + + +* ---------------------------------------------------------------------------- +* 4. Define basic objects +* ---------------------------------------------------------------------------- + +/* Set mapregion half-length */ +local XL = (`xmax' - `xmin') / 2 + +/* Set mapregion half-height */ +local YL = (`ymax' - `ymin') / 2 + +/* Set mapregion center */ +local XC = `xmin' + `XL' +local YC = `ymin' + `YL' + +/* Set default scale */ +if ("`scale'" == "") local scale = 1 + +/* Set default xpos */ +if ("`xpos'" == "") local xpos = 0 + +/* Set default ypos */ +if ("`ypos'" == "") local ypos = -110 + +/* Set default bar height multiplier */ +if ("`size'" == "") local size = 1 + +/* Set default fill color */ +if (`"`fcolor'"' == "") local fcolor "black" + +/* Set default outline color */ +if (`"`ocolor'"' == "") local ocolor "black" + +/* Set default outline size */ +if ("`osize'" == "") local osize "vthin" + +/* Set default outline alignment */ +if ("`oalign'" == "") local oalign "center" + +/* Set default label */ +if (`"`label'"' == "") local label "Units" + +/* Set default text color */ +if (`"`tcolor'"' == "") local tcolor "black" + +/* Set default text size */ +if ("`tsize'" == "") local tsize "*1" + +/* Set default text alignment */ +if ("`talign'" == "") local talign "center" + +/* Set total bar length */ +local BLEN = `units' / `scale' + +/* Set partial bar length */ +local PLEN = `BLEN' / 5 + +/* Set bar height */ +local BHEI = min(`xmax' - `xmin', `ymax' - `ymin') / 70 * 0.7 * `size' + +/* Set bar coordinates */ +if (`xpos' == 0) { + local X1 = `XC' - `BLEN' / 2 + local X2 = `XC' + `BLEN' / 2 +} +if (`xpos' < 0) { + local X1 = `XC' + `xpos' / 100 * `XL' + local X2 = `X1' + `BLEN' +} +if (`xpos' > 0) { + local X2 = `XC' + `xpos' / 100 * `XL' + local X1 = `X2' - `BLEN' +} +local Y1 = `YC' + `ypos' / 100 * `YL' - `BHEI' / 2 +local Y2 = `YC' + `ypos' / 100 * `YL' + `BHEI' / 2 +local X1a = `X1' + `PLEN' +local X2a = `X1' + `PLEN' * 2 +local X1b = `X1' + `PLEN' * 3 +local X2b = `X1' + `PLEN' * 4 + +/* Set label x-coordinate */ +local XLBL = `X1' + `BLEN' / 2 + +/* Set text size */ +local Q = strpos("`tsize'","*") +if (`Q' != 0) { + local tsize = subinstr("`tsize'","*","",.) + local tsize = `tsize' * 0.75 + local tsize "*`tsize'" +} + + + + +* ---------------------------------------------------------------------------- +* 5. Parse style lists +* ---------------------------------------------------------------------------- + +/* Parse option fcolor() */ +local fcolor : word 1 of `fcolor' + +/* Parse option ocolor() */ +local ocolor : word 1 of `ocolor' + +/* Parse option osize() */ +local osize : word 1 of `osize' + +/* Parse option oalign() */ +local oalign : word 1 of `oalign' + +/* Parse option tcolor() */ +local tcolor : word 1 of `tcolor' + +/* Parse option tsize() */ +local tsize : word 1 of `tsize' + +/* Parse option talign() */ +local talign : word 1 of `talign' + + + + +* ---------------------------------------------------------------------------- +* 6. Compose command +* ---------------------------------------------------------------------------- + +if c(stata_version) >= 15 { + local LA `"la("`oalign'")"' + local TA `"la("`talign'")"' +} + +/* Compose command */ +local GRAPH `"(scatteri `Y1' `X1' `Y2' `X1' `Y2' `X2' `Y1' `X2',"' +local GRAPH `"`GRAPH' recast(area) nodropbase cmissing(n) fc(`fcolor')"' +local GRAPH `"`GRAPH' fi(100) lc(`ocolor') lw(`osize') `LA') "' +local GRAPH `"`GRAPH'(scatteri `Y1' `X1a' `Y2' `X1a' `Y2' `X2a'"' +local GRAPH `"`GRAPH' `Y1' `X2a' . . `Y1' `X1b' `Y2' `X1b'"' +local GRAPH `"`GRAPH' `Y2' `X2b' `Y1' `X2b', recast(area) nodropbase"' +local GRAPH `"`GRAPH' cmissing(n) fc(white) lc(`ocolor') lw(`osize') `LA') "' +local GRAPH `"`GRAPH'(scatteri `Y1' `XLBL' (6) "`label'""' +local GRAPH `"`GRAPH' `Y2' `X1' (12) "0" `Y2' `X2' (12) "`units'","' +local GRAPH `"`GRAPH' msymbol(i) mlabsize(`tsize') mlabcolor(`tcolor')"' +local GRAPH `"`GRAPH' mlabgap(*0.1) `TA') "' + + + + +* ---------------------------------------------------------------------------- +* 7. Return info of interest +* ---------------------------------------------------------------------------- + +/* Return command */ +return local command `"`GRAPH'"' + +/* Return min/max coordinates */ +return local xmin = `X1' - `BLEN' * 0.05 +return local xmax = `X2' + `BLEN' * 0.05 +return local ymin = `Y1' - `BHEI' * 4 +return local ymax = `Y2' + `BHEI' * 4 + + + + +* ---------------------------------------------------------------------------- +* 8. End program +* ---------------------------------------------------------------------------- + +end + + + diff --git a/notebooks/msna/Codes/ado/stata.trk b/notebooks/msna/Codes/ado/stata.trk new file mode 100644 index 00000000..c888baca --- /dev/null +++ b/notebooks/msna/Codes/ado/stata.trk @@ -0,0 +1,47 @@ +* 00000001 +*! version 1.0.0 +* Do not erase or edit this file +* It is used by Stata to track the ado and help +* files you have installed. + +S http://fmwww.bc.edu/repec/bocode/s +N spmap.pkg +D 6 Nov 2023 +U 1 +d 'SPMAP': module to visualize spatial data +d +d spmap is aimed at visualizing several kinds of spatial data, +d and is particularly suited for drawing thematic maps and +d displaying the results of spatial data analyses. Proper +d specification of spmap options and suboptions, combined with the +d availability of properly formatted spatial data, allows the user +d to draw several kinds of maps, including choropleth maps, +d proportional symbol maps, pin maps, pie chart maps, and +d noncontiguous area cartograms. spmap completely supersedes its +d predecessor tmap. +d +d KW: maps +d KW: thematic +d KW: spatial data +d KW: choropleth +d +d Requires: Stata version 9.2 +d +d Distribution-Date: 20180118 +d +d Author: Maurizio Pisati, University of Milano Bicocca - Italy +d Support: email maurizio.pisati@@unimib.it +d +f s\spmap.ado +f s\spmap.hlp +f s\spmap_arrow.ado +f s\spmap_color.ado +f s\spmap_diagram.ado +f s\spmap_examples.ado +f s\spmap_label.ado +f s\spmap_line.ado +f s\spmap_point.ado +f s\spmap_polygon.ado +f s\spmap_psl.ado +f s\spmap_scalebar.ado +e diff --git a/notebooks/msna/Codes/maps.do b/notebooks/msna/Codes/maps.do new file mode 100644 index 00000000..7cc55ebc --- /dev/null +++ b/notebooks/msna/Codes/maps.do @@ -0,0 +1,147 @@ +******************************************************************** +* Multi-Sectoral Needs Assesment +* Do-file: Maps +* Autor: Ivonne Lara (ivilaco@hotmail.com)(ilaracortes@worldbank.org) +******************************************************************** + + clear all + + cd "C:\Users\wb607344\OneDrive - WBG\Documents\Tasks\Syria\MSNA" + global msna "C:\Users\wb607344\OneDrive - WBG\Documents\Tasks\Syria\MSNA" + global data "${msna}\Data" + global output "${msna}\Output" + + sysdir set PLUS "${msna}\Codes\ado" + + * Install packages + *ssc install spmap + +******************* Data processing Population + +******************* Data processing Humanitarian Aid + + *import delimited "${data}\Coded\aid_dis_2022.csv", clear + import delimited "${data}\Coded\pop_2022.csv", clear + + * Location type + cap replace type_location = "1" if type_location == "Camp" + cap replace type_location = "2" if type_location == "Community" + cap replace type_location = "3" if type_location == "Neighborhood" + + cap destring type_location, replace + + cap lab define type_loc 1 "Camp" 2 "Community" 3 "Neighborhood" + cap lab values type_location type_loc + + * HH population type + cap replace hh_pop_type = "1" if hh_pop_type == "Host population" + cap replace hh_pop_type = "2" if hh_pop_type == "Internally displaced person (IDP)" + cap replace hh_pop_type = "3" if hh_pop_type == "Returnee (returned in 2022)" + + cap destring hh_pop_type, replace + + cap lab define hh_pop 1 "Host population" 2 "Internally displaced person (IDP)" 3 "Returnee (returned in 2022)" + cap lab values hh_pop_type hh_pop + + * Sub District + rename subdis_code ADM3_PCODE + + /* Percentage of hh with access to aid + gen catIDPs_new=. + replace catIDPs_new=1 if per_aid_hh_rec==0 + replace catIDPs_new=2 if per_aid_hh_rec>0 & per_aid_hh_rec<25 + replace catIDPs_new=3 if per_aid_hh_rec>=25 & per_aid_hh_rec<50 + replace catIDPs_new=4 if per_aid_hh_rec>=50 & per_aid_hh_rec<75 + replace catIDPs_new=5 if per_aid_hh_rec>=75 + + label define cat 1 "0%" 2 "1% - 24%" 3 "25% - 49%" 4 "50% - 74%" 5 "75% - 100%" + label values catIDPs_new cat + */ + + * Population + gen catIDPs_new=. + replace catIDPs_new=1 if pop==0 + replace catIDPs_new=2 if pop>0 & pop<=325 + replace catIDPs_new=3 if pop>325 & pop<=650 + replace catIDPs_new=4 if pop>650 & pop<=975 + replace catIDPs_new=5 if pop>975 & pop<=1300 + replace catIDPs_new=6 if pop>1300 & pop<=1625 + replace catIDPs_new=7 if pop>1625 & pop<=1950 + replace catIDPs_new=8 if pop>1950 & pop<=2275 + replace catIDPs_new=9 if pop>2275 + + label define cat 1 "0" 2 "1 - 325" 3 "326 - 650" 4 "651 - 975" 5 "976 - 1300" 6 "1301 - 1625" 7 "1626 - 1950" 8 "1951 - 2275" 9 "2276 - 2600" + label values catIDPs_new cat + */ + + +******************* Map + + * Population + forvalues i=1/3 { + + preserve + + keep if hh_pop_type == `i' + cap merge 1:m ADM3_PCODE using "${data}\Raw\syria3.dta", keepusing(_ID) + + spmap catIDPs_new using "${data}\Raw\syria3_shp.dta", /// + id(_ID) clm(u) legend(pos(4)) fcolor(Reds) ndo(gs10) /// + legend(title("Total population", size(2.3) justification(left))) + + graph export "${output}\pop_`i'.png", replace + + restore + } + + *spshape2dta "${data}\Raw\syr_admbnda_adm3_uncs_unocha_20201217-polygon.shp", replace saving(syria3) + + * Camp + preserve + + keep if type_location == 1 & hh_pop_type == 2 + cap merge 1:m ADM3_PCODE using "${data}\Raw\syria3.dta", keepusing(_ID) + + spmap catIDPs_new using "${data}\Raw\syria3_shp.dta", /// + id(_ID) clm(u) legend(pos(4)) fcolor(Greens) ndo(gs10) /// + legend(title("Percentage of households with" "access to humanitarian aid", size(2.3) justification(left))) + + cap graph export "${output}\map_per_hh_aid_1_2.png", replace + + restore + + * Community + forvalues i = 1/3 { + + preserve + + keep if type_location == 2 & hh_pop_type == `i' + cap merge 1:m ADM3_PCODE using "${data}\Raw\syria3.dta", keepusing(_ID) + + spmap catIDPs_new using "${data}\Raw\syria3_shp.dta", /// + id(_ID) clm(u) legend(pos(4)) fcolor(Blues) ndo(gs10) /// + legend(title("Percentage of households with" "access to humanitarian aid", size(2.3) justification(left))) + + cap graph export "${output}\map_per_hh_aid_2_`i'.png", replace + + restore + + } + + * Neighborhood + forvalues i = 1/3 { + + preserve + + keep if type_location == 3 & hh_pop_type == `i' + cap merge 1:m ADM3_PCODE using "${data}\Raw\syria3.dta", keepusing(_ID) + + spmap catIDPs_new using "${data}\Raw\syria3_shp.dta", /// + id(_ID) clm(u) legend(pos(4)) fcolor(Oranges) ndo(gs10) /// + legend(title("Percentage of households with" "access to humanitarian aid", size(2.3) justification(left))) + + cap graph export "${output}\map_per_hh_aid_3_`i'.png", replace + + restore + + } From fd2996af7b4894f92a5de2dbca58a7ed6acc0917 Mon Sep 17 00:00:00 2001 From: ivilaco Date: Mon, 27 Nov 2023 21:23:51 -0500 Subject: [PATCH 2/5] Code updates --- notebooks/msna/0_master.R | 8 +- notebooks/msna/Codes/1_cleaning.R | 185 ++++++++++++++++++++---- notebooks/msna/Codes/2_demographics.R | 74 +++++++--- notebooks/msna/Codes/3_1_conflict.R | 40 ++--- notebooks/msna/Codes/3_2_aid.R | 53 +++---- notebooks/msna/Codes/3_3_displacement.R | 7 +- notebooks/msna/Codes/3_4_hh_welfare.R | 20 +-- notebooks/msna/Codes/3_5_maps.R | 22 --- 8 files changed, 272 insertions(+), 137 deletions(-) delete mode 100644 notebooks/msna/Codes/3_5_maps.R diff --git a/notebooks/msna/0_master.R b/notebooks/msna/0_master.R index ef3d392a..fe72f55e 100644 --- a/notebooks/msna/0_master.R +++ b/notebooks/msna/0_master.R @@ -6,6 +6,7 @@ #install.packages(c("here", "tidyverse", "visdat", "summarytools", "readxl", "ggplot2", "Hmisc", "devtools")) #devtools::install_github("hadley/scales") +#install.packages('RMySQL', repos='http://cran.us.r-project.org') library(here) library(tidyverse) @@ -18,12 +19,17 @@ library(scales) library(dplyr) library(viridis) library(ggrepel) +library(sf) +library(haven) +library(RColorBrewer) -# Colors ----------------------------------------------------------------------- +# Colors and shapefiles -------------------------------------------------------- pie_colors <- c("#66c2e0", "#fae10b", "#fc8d62", "darkseagreen3", "lightpink1", "lightsteelblue1") bar_colors <- c("#66c2e0", "#fae10b", "#fc8d62") +syria_shp <- st_read(here("Data", "Raw", "syr_admbnda_adm3_uncs_unocha_20201217-polygon.shp")) + # Codes ------------------------------------------------------------------------ codes <- "C:/Users/wb607344/Downloads/syria-economic-monitor/notebooks/msna/Codes" diff --git a/notebooks/msna/Codes/1_cleaning.R b/notebooks/msna/Codes/1_cleaning.R index 26854a52..cbde6fe9 100644 --- a/notebooks/msna/Codes/1_cleaning.R +++ b/notebooks/msna/Codes/1_cleaning.R @@ -16,38 +16,163 @@ raw_2022 <- sheet = "Dataset - households" ) -# Data quality ----------------------------------------------------------------- - -# Check missing values for each variable -#missing_values <- raw_2022 %>% -# summarise_all(~sum(is.na(.))) - -# Display missing values -#print(missing_values) - -# To see unique values and frequency -#table(raw_2022$HoH_employ) +raw_2023 <- + read_xlsx( + here( + "Data", + "Raw", + "MSNA2023_dataset.xlsx" + ), + sheet = "Dataset - households" + ) # Data preparation ------------------------------------------------------------- -msna_2022 <- - raw_2022 %>% - select( - id, q_k7, q_k8, q_k9, q_k10, q_k11, q_k6, q_k12, q_r1, q_r2, q_r3, q_r12, q_r1, - q_r2, q_r3, q_r12, q_h3, q_h1, q_h2, q_8_4_1, q_16_8_b, q_8_7, q_16_8, q_16_8, - q_16_8, q_16_8, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_8_1, q_8_1_1, q_17_1, - q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_1, q_7_2, q_7_2_1, q_7_4, - q_7_6, q_7_7, q_7_9_1, q_7_9_2, q_7_9_3, q_10_1, q_10_4, q_11_1, q_10_4_e, - q_15_1, q_9_2, q_9_4, q_9_4_1, q_9_3, q_16_2, q_16_3_1, q_16_3_2, q_16_3_3, - q_16_4_currency, q_16_4_a, q_16_4_b, starts_with("q_8_1_1_"), q_16_4 + # 2022 + msna_2022 <- + raw_2022 %>% + filter(q_k10 != "Neighborhood") %>% + separate( + q_16_8, + into = c("safety_1", "safety_2", "safety_3", "safety_4", "safety_5"), + sep = "; " + ) %>% + separate( + q_10_4, + into = c("issues_1", "issues_2", "issues_3", "issues_4", "issues_5"), + sep = "; " + ) %>% + mutate(q_17_1 = ifelse(q_17_1 %in% c("Don't know / unsure", "Prefer not to answer"), NA, q_17_1), + q_17_3 = ifelse(q_17_3 == "Prefer to not answer", NA, q_17_3), + q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), + q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", + "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), + q_7_1 = ifelse(q_7_1 == "Internally displaced person (IDP)" & q_k10 == "Camp", "IDPs in camps", q_7_1), + q_7_1 = ifelse(q_7_1 == "Internally displaced person (IDP)" & q_k10 != "Camp", "IDPs out of camps", q_7_1), + q_7_1 = ifelse(q_7_1 == "Host population", "Host (Residents)", q_7_1), + q_7_1 = ifelse(q_7_1 == "Returnee (returned in 2022)", "Returnees (2022)", q_7_1), + q_r3 = ifelse(q_r3 == "Widow / Widower", "Widowed", q_r3), + q_8_7 = ifelse(q_8_7 == "Don't know / unsure", "Don't know", q_8_7), + q_8_5_0 = ifelse(q_8_5_0 == "Don't know / unsure", "Don't know", q_8_5_0), + q_8_5_1 = ifelse(q_8_5_1 == "Don't know / unsure", "Don't know", q_8_5_1), + q_8_5_2 = ifelse(q_8_7 == "Don't know / unsure", "Don't know", q_8_5_2), + q_8_5_3 = ifelse(q_8_7 == "Don't know / unsure", "Don't know", q_8_5_3), + q_11_1 = ifelse(q_11_1 == "Not enough water to meet any of the above needs", "No", "Yes"), + q_15_1 = ifelse(q_15_1 %in% c("16-21 hours per day", "22+ hours per day"), "16+ hours per day", q_15_1), + q_16_4_b = q_16_4_b/0.0071, + q_16_4_a = ifelse(q_16_4_currency == "Turkish Lira (TRY)", q_16_4_b, q_16_4_a), # SYP to TRY on August 1, 2022 + year = 2022 + ) %>% + rename( + limit = q_16_3_1, + income = q_16_4_a ) %>% - mutate(q_17_1 = ifelse(q_17_1 %in% c("Don't know / unsure", "Prefer not to answer"), NA, q_17_1), - q_17_3 = ifelse(q_17_3 %in% c("Don't know/unsure", "Prefer to not answer"), NA, q_17_3), - q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), - q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", - "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), - q_7_1 = ifelse(q_7_1 == "Internally displaced person (IDP)", "IDP", q_7_1), - q_7_1 = ifelse(q_7_1 == "Returnee (returned in 2022)", "Returnee (2022)", q_7_1) - ) %>% - filter(q_k10 != "Neighborhood") + select( + id, q_7_1, q_k7, q_k8, q_k9, q_r1, q_r2, q_r3, q_r12, q_8_7, safety_1, + safety_2, safety_3, safety_4, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_17_1, + q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_2, q_7_2_1, q_7_4, q_7_6, q_7_7, + q_7_9_1, q_7_9_2, q_7_9_3, issues_1, issues_2, issues_3, q_10_1, q_11_1, + q_15_1, q_9_4_1, q_16_2, limit, income, q_16_4, year + ) + + # 2023 + msna_2023 <- + raw_2023 %>% + separate( + safety_boys, + into = c("safety_1", "safetyb"), + sep = " " + ) %>% + separate( + safety_girls, + into = c("safety_2", "safetyg"), + sep = " " + ) %>% + separate( + safety_women, + into = c("safety_3", "safetyw"), + sep = " " + ) %>% + separate( + safety_men, + into = c("safety_4", "safetym"), + sep = " " + ) %>% + separate( + unmet_needs, + into = c("q_16_1_1", "q_16_1_2", "q_16_1_3"), + sep = " " + ) %>% + separate( + q_7_9, + into = c("q_7_9_1", "q_7_9_2", "q_7_9_3", "q_7_9_4"), + sep = " " + ) %>% + separate( + q_10_4, + into = c("issues_1", "issues_2", "issues_3", "issues_4", "issues_5"), + sep = "; " + ) %>% + separate( + q_16_3, + into = c("limit", "limit_o"), + sep = "; " + ) %>% + mutate( + q_7_1 = ifelse(q_7_1 == "Returnees", "Returnees (2023)", q_7_1), + safety_1 = str_replace_all(safety_1, "_", " "), + safety_2 = str_replace_all(safety_2, "_", " "), + safety_3 = str_replace_all(safety_3, "_", " "), + safety_4 = str_replace_all(safety_4, "_", " "), + q_16_1_1 = str_replace_all(q_16_1_1, "_", " "), + q_16_1_2 = str_replace_all(q_16_1_2, "_", " "), + q_16_1_3 = str_replace_all(q_16_1_3, "_", " "), + q_7_9_1 = str_replace_all(q_7_9_1, "_", " "), + q_7_9_2 = str_replace_all(q_7_9_2, "_", " "), + q_7_9_3 = str_replace_all(q_7_9_3, "_", " "), + issues_1 = str_replace_all(issues_1, "_", " "), + issues_2 = str_replace_all(issues_2, "_", " "), + issues_3 = str_replace_all(issues_3, "_", " "), + limit = str_replace_all(limit, "_", " "), + q_17_3 = ifelse(q_17_3 == "Prefer to not answer", NA, q_17_3), + q_17_3 = ifelse(q_17_3 == "Neither satisfied nor dissatisfied with all assistance/access to services received", "Don’t know/unsure", q_17_3), + q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), + q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", + "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), + q_11_1 = ifelse(q_11_1 %in% c("Never (0 days)", "Don’t know/unsure", " Rarely (1–2 days)", "Sometimes (3–10 days)"), "No", "Yes"), + q_15_1 = ifelse(q_15_1 == 0, "0 hours per day", q_15_1), + q_15_1 = ifelse(q_15_1 %in% 1:2, "1-2 hours per day", q_15_1), + q_15_1 = ifelse(q_15_1 >= 3 & q_15_1 <= 8, "3-8 hours per day", q_15_1), + q_15_1 = ifelse(q_15_1 >= 9 & q_15_1 <= 15, "9-15 hours per day", q_15_1), + q_15_1 = ifelse(q_15_1 >= 16, "16+ hours per day", q_15_1), + income = q_16_4_a + q_16_4_b + q_16_4_c + q_16_4_d + q_16_4_e + q_16_4_f + + q_16_4_g + q_16_4_h + q_16_4_i + q_16_4_j + q_16_4_k + q_16_4_l + q_16_4_m, + income = ifelse(q_16_4_currency == "Turkish Lira (TRY)", income/0.0020, income), # SYP to TRY on September 20, 2023 + income = ifelse(q_16_4_currency == "US Dollars (USD)", income/0.000076, income), # SYP to USD on September 20, 2023 + year = 2023 + ) %>% + select( + id, q_7_1, q_k7, q_k8, q_k9, q_r1, q_r2, q_r3, q_r12, q_8_7, safety_1, + safety_2, safety_3, safety_4, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_17_1, + q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_2, q_7_2_1, q_7_4, q_7_6, q_7_7, + aid_kind, q_7_9_1, q_7_9_2, q_7_9_3, issues_1, issues_2, issues_3, q_10_1, + q_11_1, nutrition_3m, q_15_1, barriers_healthcare, q_16_2, q_16_4, limit, + unex_events, event_hh_affected, year + ) + +# Data append ------------------------------------------------------------------ + + msna <- bind_rows(msna_2022, msna_2023) + +# Data quality ----------------------------------------------------------------- + + # Check missing values for each variable + #missing_values <- raw_2022 %>% + # summarise_all(~sum(is.na(.))) + + # Display missing values + #print(missing_values) + + # To see unique values and frequency + #table(raw_2022$HoH_employ) \ No newline at end of file diff --git a/notebooks/msna/Codes/2_demographics.R b/notebooks/msna/Codes/2_demographics.R index 857f7d71..776ed54e 100644 --- a/notebooks/msna/Codes/2_demographics.R +++ b/notebooks/msna/Codes/2_demographics.R @@ -4,37 +4,69 @@ # 2_demographics ###################################################################### +############################### +# MSNA 2022 +############################### + # Population distribution ------------------------------------------------------ + # 2022 pop_2022 <- msna_2022 %>% group_by(q_7_1, q_k9) %>% summarise(pop = sum(q_r12, na.rm = TRUE), - .groups = 'drop') + .groups = 'drop') %>% + mutate( + subdis_code = str_split(q_k9, " - ", simplify = TRUE)[, 1], + subdis_name = str_split(q_k9, " - ", simplify = TRUE)[, 2], + ADM3_PCODE = subdis_code) %>% + select(ADM3_PCODE, subdis_code, subdis_name, q_7_1, pop) + + unique_pop <- unique(pop_2022$q_7_1) - # Variables processing - pop_2022 <- pop_2022 %>% + for (i in unique_pop) { + + subset_data <- pop_2022 %>% filter(q_7_1 == i) + merged_data <- left_join(syria_shp, subset_data, by = "ADM3_PCODE") + + pop_map <- ggplot(merged_data) + + geom_sf(aes(fill = pop)) + + scale_fill_gradient(low = "lightblue", high = "darkblue", na.value = "white") + + ggtitle(i) + + theme_minimal() + + theme(legend.position = "right") + + labs(fill = "Population") + + ggsave(here("Output", "2022", paste0("/pop_", i, ".png")), plot = pop_map, width = 7, height = 6, units = "in", dpi = 300) + } + + # 2023 + pop_2023 <- msna_2023 %>% + group_by(q_7_1, q_k9) %>% + summarise(pop = sum(q_r12, na.rm = TRUE), + .groups = 'drop') %>% mutate( subdis_code = str_split(q_k9, " - ", simplify = TRUE)[, 1], subdis_name = str_split(q_k9, " - ", simplify = TRUE)[, 2], - hh_pop_type = as.numeric(as.character(case_when( - q_7_1 == "Host population" ~ "1", - q_7_1 == "Internally displaced person (IDP)" ~ "2", - q_7_1 == "Returnee (returned in 2022)" ~ "3", - TRUE ~ as.character(q_7_1) - ))), - ADM3_PCODE = subdis_code, - catIDPs_new = cut(pop, breaks = c(-Inf, 0, 325, 650, 975, 1300, 1625, 1950, 2275, Inf), - labels = c("0", "1 - 325", "326 - 650", "651 - 975", "976 - 1300", "1301 - 1625", "1626 - 1950", "1951 - 2275", "2276 - 2600")) - ) %>% - select(ADM3_PCODE, subdis_code, subdis_name, hh_pop_type, pop, catIDPs_new) + ADM3_PCODE = subdis_code) %>% + select(ADM3_PCODE, subdis_code, subdis_name, q_7_1, pop) + + unique_pop <- unique(pop_2023$q_7_1) - pop_2022 %>% - write_csv( - here("Data", - "Coded", - "pop_2022.csv" - ) - ) + for (i in unique_pop) { + + subset_data <- pop_2023 %>% filter(q_7_1 == i) + merged_data <- left_join(syria_shp, subset_data, by = "ADM3_PCODE") + + pop_map <- ggplot(merged_data) + + geom_sf(aes(fill = pop)) + + scale_fill_gradient(low = "lightblue", high = "darkblue", na.value = "white") + + ggtitle(i) + + theme_minimal() + + theme(legend.position = "right") + + labs(fill = "Population") + + ggsave(here("Output", "2023", paste0("/pop_", i, ".png")), plot = pop_map, width = 7, height = 6, units = "in", dpi = 300) + } # HH characteristics ---------------------------------------------------- diff --git a/notebooks/msna/Codes/3_1_conflict.R b/notebooks/msna/Codes/3_1_conflict.R index 3b8df903..10a8ac4f 100644 --- a/notebooks/msna/Codes/3_1_conflict.R +++ b/notebooks/msna/Codes/3_1_conflict.R @@ -40,12 +40,7 @@ ggsave(here("Output", "bar_unsaf_girls.png"), bar_chart, width = 10, height = 6) # Main safety and security concerns in the past 3 months ----------------------- safety_2022 <- msna_2022 %>% - select(id, q_16_8, q_k10) %>% - separate( - q_16_8, - into = c("safety_1", "safety_2", "safety_3", "safety_4", "safety_5"), - sep = "; " - ) %>% + select(id, starts_with("safety_"), q_k10) %>% pivot_longer(cols = starts_with("safety"), names_to = "safety_q", values_to = "safety_r") %>% filter(!is.na(safety_r), safety_r != "Don't know/unsure", safety_r != "Prefer not to answer") %>% mutate(ones = 1, @@ -94,17 +89,28 @@ bar_chart <- ggplot(safety_2022, aes(x = percentage, y = safety_r, fill = q_k10) ggsave(here("Output", "bar_sec.png"), bar_chart, width = 9, height = 6) -# High levels of stress experienced by a hh member ------------------------------ - -stress_2022 <- msna_2022 %>% - select(starts_with("q_8_5_"), q_k10, q_7_1) %>% - mutate(stress = ifelse(q_8_5_0 == "Yes" | q_8_5_1 == "Yes" | q_8_5_2 == "Yes" | q_8_5_3 == "Yes", "Yes", "No"), - stress = ifelse((q_8_5_0 == "No" & is.na(stress)) | (q_8_5_1 == "No" & is.na(stress)) | (q_8_5_2 == "No" & is.na(stress)) | (q_8_5_3 == "No" & is.na(stress)), "No", stress), - ones = 1) %>% - filter(!is.na(stress)) %>% - group_by(stress, q_k10, q_7_1) %>% - summarise(total = sum(ones, na.rm = TRUE), - .groups = 'drop') +# Levels of stress experienced by a hh member ---------------------------------- + + # 2022 + stress_2022 <- msna_2022 %>% + select(starts_with("q_8_5_"), q_7_1) %>% + mutate(stress = ifelse(q_8_5_0 == "Yes" | q_8_5_1 == "Yes" | q_8_5_2 == "Yes" | q_8_5_3 == "Yes", "Yes", "No"), + stress = ifelse((q_8_5_0 == "No" & is.na(stress)) | (q_8_5_1 == "No" & is.na(stress)) | (q_8_5_2 == "No" & is.na(stress)) | (q_8_5_3 == "No" & is.na(stress)), "No", stress), + ones = 1) %>% + filter(!is.na(stress)) %>% + group_by(stress, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') + # 2023 + stress_2023 <- msna_2023 %>% + select(starts_with("q_8_5_"), q_7_1) %>% + mutate(stress = ifelse(q_8_5_0 == "Yes" | q_8_5_1 == "Yes" | q_8_5_2 == "Yes" | q_8_5_3 == "Yes", "Yes", "No"), + stress = ifelse((q_8_5_0 == "No" & is.na(stress)) | (q_8_5_1 == "No" & is.na(stress)) | (q_8_5_2 == "No" & is.na(stress)) | (q_8_5_3 == "No" & is.na(stress)), "No", stress), + ones = 1) %>% + filter(!is.na(stress)) %>% + group_by(stress, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') unique_q_k10 <- unique(stress_2022$q_k10) diff --git a/notebooks/msna/Codes/3_2_aid.R b/notebooks/msna/Codes/3_2_aid.R index a38137f3..3fcd7e33 100644 --- a/notebooks/msna/Codes/3_2_aid.R +++ b/notebooks/msna/Codes/3_2_aid.R @@ -4,41 +4,42 @@ # 3_2_aid ###################################################################### -# % HH having received aid in the 3 months ------------------------------------- +# % of HH having received aid in the 3 months ---------------------------------- aid_2022 <- msna_2022 %>% group_by(q_k10, q_k9, q_7_1) %>% summarise( - per_aid_hh_rec = mean(q_17_1 == "Yes", na.rm = TRUE) * 100, + per_aid_hh = mean(q_17_1 == "Yes", na.rm = TRUE) * 100, .groups = 'drop' - ) - - aid_2022 <- aid_2022 %>% + ) %>% mutate( subdis_code = str_split(q_k9, " - ", simplify = TRUE)[, 1], subdis_name = str_split(q_k9, " - ", simplify = TRUE)[, 2], - type_location = as.numeric(as.character(case_when( - as.character(q_k10) == "Camp" ~ "1", - as.character(q_k10) == "Community" ~ "2", - as.character(q_k10) == "Neighborhood" ~ "3", - TRUE ~ as.character(q_k10) - ))), - ADM3_PCODE = subdis_code, - catIDPs_new = cut(per_aid_hh_rec, breaks = c(-Inf, 0, 25, 50, 75, Inf), - labels = c("0%", "1% - 24%", "25% - 49%", "50% - 74%", "75% - 100%")) - ) %>% - select(ADM3_PCODE, subdis_code, subdis_name, type_location, per_aid_hh_rec, catIDPs_new) + ADM3_PCODE = subdis_code) %>% + select(ADM3_PCODE, subdis_code, subdis_name, q_k10, per_aid_hh, q_7_1) + + unique_q_k10 <- unique(aid_2022$q_k10) + unique_pop <- unique(pop_2022$q_7_1) + + for (i in unique_pop) { + for (j in unique_q_k10) { + + subset_data <- aid_2022 %>% filter(q_7_1 == i, q_k10 == j) + merged_data <- left_join(syria_shp, subset_data, by = "ADM3_PCODE") + + pop_map <- ggplot(merged_data) + + geom_sf(aes(fill = per_aid_hh)) + + scale_fill_gradient(low = "lightblue", high = "darkblue", na.value = "white") + + ggtitle(i) + + theme_minimal() + + theme(legend.position = "right") + + labs(fill = "Percentage") + + ggsave(here("Output", "2022", paste0("/aid_", i, "_", j, ".png")), plot = pop_map, width = 7, height = 6, units = "in", dpi = 300) + } + } + - levels(aid_2022$type_location) <- c("Camp", "Community", "Neighborhood") - - aid_2022 %>% - write_csv( - here("Data", - "Coded", - "aid_dis_2022.csv" - ) - ) - # Aid satisfaction ------------------------------------------------------------- aid_2022 <- msna_2022 %>% diff --git a/notebooks/msna/Codes/3_3_displacement.R b/notebooks/msna/Codes/3_3_displacement.R index 30256d9f..037ef0c8 100644 --- a/notebooks/msna/Codes/3_3_displacement.R +++ b/notebooks/msna/Codes/3_3_displacement.R @@ -226,12 +226,7 @@ for (value in unique_q_k10) { # Adequacy issues in the hh shelter -------------------------------------------- issues_2022 <- msna_2022 %>% - select(id, q_10_4, q_k10, q_7_1) %>% - separate( - q_10_4, - into = c("issues_1", "issues_2", "issues_3", "issues_4", "issues_5"), - sep = "; " - ) %>% + select(id, starts_with("issues_"), q_k10, q_7_1) %>% pivot_longer(cols = starts_with("issues"), names_to = "issues_q", values_to = "issues_r") %>% filter(!is.na(issues_r)) %>% mutate(ones = 1, diff --git a/notebooks/msna/Codes/3_4_hh_welfare.R b/notebooks/msna/Codes/3_4_hh_welfare.R index d47d42e7..58a98c42 100644 --- a/notebooks/msna/Codes/3_4_hh_welfare.R +++ b/notebooks/msna/Codes/3_4_hh_welfare.R @@ -7,10 +7,7 @@ # % of HHs by number of hours of access to electricity ------------------------- electr_2022 <- msna_2022 %>% - filter(!is.na(q_15_1)) %>% - mutate( - q_15_1 = ifelse(q_15_1 %in% c("16-21 hours per day", "22+ hours per day"), "16+ hours per day", q_15_1), - ) + filter(!is.na(q_15_1)) unique_q_k10 <- unique(wat_2022$q_k10) @@ -48,7 +45,7 @@ for (value in unique_q_k10) { wat_2022 <- msna_2022 %>% filter(!is.na(q_11_1)) %>% - mutate(q_11_1 = ifelse(q_11_1 == "Not enough water to meet any of the above needs", "No", "Yes")) + mutate() unique_q_k10 <- unique(wat_2022$q_k10) @@ -121,10 +118,7 @@ for (value in unique_q_k10) { # Main reason limiting household’s ability to meet their basic needs ----------- limits_2022 <- msna_2022 %>% - select(id, q_k10, q_16_3_1, q_7_1) %>% - rename( - limit = q_16_3_1, - ) %>% + select(id, q_k10, limit, q_7_1) %>% mutate(id = id, ones = 1, limit = ifelse(limit %in% c("Other (please specify)", @@ -220,10 +214,8 @@ for (value in unique_q_k10) { # Household income over the last 3 months -------------------------------------- income_2022 <- msna_2022 %>% - select(q_16_4_currency, q_16_4_a, q_16_4_b, q_k10, q_16_4, q_7_1) %>% - filter(q_16_4 == "Yes") %>% - mutate(q_16_4_b = q_16_4_b/0.0071, - q_16_4_a = ifelse(q_16_4_currency == "Turkish Lira (TRY)", q_16_4_b, q_16_4_a)) # SYP to TRY on August 1, 2022 + select(income, q_k10, q_16_4, q_7_1) %>% + filter(q_16_4 == "Yes") unique_q_k10 <- unique(income_2022$q_k10) @@ -232,7 +224,7 @@ for (value in unique_q_k10) { subset_data <- income_2022 %>% filter(q_k10 == value) - hist_chart <- ggplot(subset_data, aes(x = factor(q_7_1), y = q_16_4_a)) + + hist_chart <- ggplot(subset_data, aes(x = factor(q_7_1), y = income)) + geom_boxplot(fill = "lightblue", color = "blue") + labs(title = "", x = "Population type", diff --git a/notebooks/msna/Codes/3_5_maps.R b/notebooks/msna/Codes/3_5_maps.R deleted file mode 100644 index 4bae6ad7..00000000 --- a/notebooks/msna/Codes/3_5_maps.R +++ /dev/null @@ -1,22 +0,0 @@ -# Assuming you have loaded the necessary libraries -#install.packages(c("dplyr", "sf", "tmap")) - -library(dplyr) -library(sf) -library(tmap) -library(haven) - -# Location type -for (i in 1:3) { - - subset_data <- pop_2022 %>% filter(hh_pop_type == i) - - merged_data <- merge(subset_data, read_dta(here("Data", "Raw", "syria3.dta")), by.x = "ADM3_PCODE", by.y = "ADM3_PCODE", all.x = TRUE) - - sp_obj <- st_as_sf(merged_data, coords = c("longitude", "latitude"), crs = 4326) - - # Create map - png(here("Output", paste0("/pop_", i, ".png"))) - plot(sp_obj, col = "Reds", main = "Total population", add = TRUE) - dev.off() -} From 5d4cb108aeb250aa2d310c7b9e63ec22c082610f Mon Sep 17 00:00:00 2001 From: ivilaco Date: Thu, 30 Nov 2023 11:18:30 -0500 Subject: [PATCH 3/5] Code update --- notebooks/msna/0_master.R | 4 +- notebooks/msna/Codes/1_cleaning.R | 152 +++++++++++++---- notebooks/msna/Codes/2_demographics.R | 16 +- notebooks/msna/Codes/3_1_conflict.R | 99 +++++++----- notebooks/msna/Codes/3_2_aid.R | 129 ++++++++------- notebooks/msna/Codes/3_3_displacement.R | 207 +++++++++++++----------- notebooks/msna/Codes/3_4_hh_welfare.R | 195 ++++++++++++++++------ 7 files changed, 513 insertions(+), 289 deletions(-) diff --git a/notebooks/msna/0_master.R b/notebooks/msna/0_master.R index fe72f55e..6d4bfbaa 100644 --- a/notebooks/msna/0_master.R +++ b/notebooks/msna/0_master.R @@ -23,13 +23,11 @@ library(sf) library(haven) library(RColorBrewer) -# Colors and shapefiles -------------------------------------------------------- +# Colors ----------------------------------------------------------------------- pie_colors <- c("#66c2e0", "#fae10b", "#fc8d62", "darkseagreen3", "lightpink1", "lightsteelblue1") bar_colors <- c("#66c2e0", "#fae10b", "#fc8d62") -syria_shp <- st_read(here("Data", "Raw", "syr_admbnda_adm3_uncs_unocha_20201217-polygon.shp")) - # Codes ------------------------------------------------------------------------ codes <- "C:/Users/wb607344/Downloads/syria-economic-monitor/notebooks/msna/Codes" diff --git a/notebooks/msna/Codes/1_cleaning.R b/notebooks/msna/Codes/1_cleaning.R index cbde6fe9..f9116807 100644 --- a/notebooks/msna/Codes/1_cleaning.R +++ b/notebooks/msna/Codes/1_cleaning.R @@ -6,28 +6,62 @@ # Import raw data -------------------------------------------------------------- -raw_2022 <- - read_xlsx( - here( - "Data", - "Raw", - "2022-09-06_SYR_MSNA2022_dataset_HHs.xlsx" + raw_2022 <- + read_xlsx( + here( + "Data", + "Raw", + "2022-09-06_SYR_MSNA2022_dataset_HHs.xlsx" + ), + sheet = "Dataset - households" + ) + + raw_2023 <- + read_xlsx( + here( + "Data", + "Raw", + "MSNA2023_dataset.xlsx" ), - sheet = "Dataset - households" - ) - -raw_2023 <- - read_xlsx( - here( - "Data", - "Raw", - "MSNA2023_dataset.xlsx" - ), - sheet = "Dataset - households" - ) + sheet = "Dataset - households" + ) + + raw_e <- + read_xlsx( + here( + "Data", + "Raw", + "syria-earthquake-impact-20-march-2023.xlsx" + ), + sheet = "DATASET" + ) + + syria_shp <- + st_read( + here( + "Data", + "Raw", + "syr_admbnda_adm3_uncs_unocha_20201217-polygon.shp" + ) + ) # Data preparation ------------------------------------------------------------- + # Earthquake + earthquake <- raw_e %>% + select(ADM3_EN, ADM3_PCODE, ADM4_EN, ADM4_PCODE, casualties, injuries, + des_houses, damag_houses) %>% + group_by(ADM3_PCODE) %>% + summarise( + total_casualties = sum(casualties, na.rm = TRUE), + total_injuries = sum(injuries, na.rm = TRUE), + total_des_houses = sum(des_houses, na.rm = TRUE), + total_damag_houses = sum(damag_houses, na.rm = TRUE) + ) %>% + mutate( + earthquake = 1 + ) + # 2022 msna_2022 <- raw_2022 %>% @@ -72,8 +106,11 @@ raw_2023 <- safety_2, safety_3, safety_4, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_17_1, q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_2, q_7_2_1, q_7_4, q_7_6, q_7_7, q_7_9_1, q_7_9_2, q_7_9_3, issues_1, issues_2, issues_3, q_10_1, q_11_1, - q_15_1, q_9_4_1, q_16_2, limit, income, q_16_4, year - ) + q_15_1, q_9_4_1, q_16_2, limit, income, q_16_4, year, q_k11 + ) %>% + filter( + q_7_1 != "IDPs in camps" + ) # 2023 msna_2023 <- @@ -111,15 +148,37 @@ raw_2023 <- separate( q_10_4, into = c("issues_1", "issues_2", "issues_3", "issues_4", "issues_5"), - sep = "; " + sep = " " ) %>% separate( q_16_3, into = c("limit", "limit_o"), - sep = "; " + sep = " " + ) %>% + separate( + barriers_healthcare, + into = c("barr_health", "barriers_0"), + sep = " " ) %>% + separate( + unex_events, + into = c("event_1", "event_2", "event_3", "event_4"), + sep = " " + ) %>% + separate( + event_hh_affected, + into = c("affect_1", "affect_2", "affect_3", "affect_4"), + sep = " " + ) %>% mutate( q_7_1 = ifelse(q_7_1 == "Returnees", "Returnees (2023)", q_7_1), + barr_health = str_replace_all(barr_health, "_", " "), + affect_1 = str_replace_all(affect_1, "_", " "), + affect_2 = str_replace_all(affect_2, "_", " "), + affect_3 = str_replace_all(affect_3, "_", " "), + event_1 = str_replace_all(event_1, "_", " "), + event_2 = str_replace_all(event_2, "_", " "), + event_3 = str_replace_all(event_3, "_", " "), safety_1 = str_replace_all(safety_1, "_", " "), safety_2 = str_replace_all(safety_2, "_", " "), safety_3 = str_replace_all(safety_3, "_", " "), @@ -134,21 +193,29 @@ raw_2023 <- issues_2 = str_replace_all(issues_2, "_", " "), issues_3 = str_replace_all(issues_3, "_", " "), limit = str_replace_all(limit, "_", " "), - q_17_3 = ifelse(q_17_3 == "Prefer to not answer", NA, q_17_3), + q_17_3 = ifelse(q_17_3 %in% c("Prefer not to answer", "Don't know"), NA, q_17_3), q_17_3 = ifelse(q_17_3 == "Neither satisfied nor dissatisfied with all assistance/access to services received", "Don’t know/unsure", q_17_3), q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), q_11_1 = ifelse(q_11_1 %in% c("Never (0 days)", "Don’t know/unsure", " Rarely (1–2 days)", "Sometimes (3–10 days)"), "No", "Yes"), - q_15_1 = ifelse(q_15_1 == 0, "0 hours per day", q_15_1), - q_15_1 = ifelse(q_15_1 %in% 1:2, "1-2 hours per day", q_15_1), - q_15_1 = ifelse(q_15_1 >= 3 & q_15_1 <= 8, "3-8 hours per day", q_15_1), - q_15_1 = ifelse(q_15_1 >= 9 & q_15_1 <= 15, "9-15 hours per day", q_15_1), - q_15_1 = ifelse(q_15_1 >= 16, "16+ hours per day", q_15_1), - income = q_16_4_a + q_16_4_b + q_16_4_c + q_16_4_d + q_16_4_e + q_16_4_f + - q_16_4_g + q_16_4_h + q_16_4_i + q_16_4_j + q_16_4_k + q_16_4_l + q_16_4_m, + q_15_1 = ifelse(q_15_1 == 0, "0 hours per day", + ifelse(q_15_1 %in% 1:2, "1-2 hours per day", + ifelse(q_15_1 >= 3 & q_15_1 <= 8, "3-8 hours per day", + ifelse(q_15_1 >= 9 & q_15_1 <= 15, "9-15 hours per day", + ifelse(q_15_1 >= 16, "16+ hours per day", q_15_1))))), + income = coalesce(q_16_4_a, 0) + coalesce(q_16_4_b, 0) + coalesce(q_16_4_c, 0) + + coalesce(q_16_4_d, 0) + coalesce(q_16_4_e, 0) + coalesce(q_16_4_f, 0) + + coalesce(q_16_4_g, 0) + coalesce(q_16_4_h, 0) + coalesce(q_16_4_i, 0) + + coalesce(q_16_4_j, 0) + coalesce(q_16_4_k, 0) + coalesce(q_16_4_l, 0) + + coalesce(q_16_4_m, 0), income = ifelse(q_16_4_currency == "Turkish Lira (TRY)", income/0.0020, income), # SYP to TRY on September 20, 2023 income = ifelse(q_16_4_currency == "US Dollars (USD)", income/0.000076, income), # SYP to USD on September 20, 2023 + aid_kind = str_replace_all(aid_kind, "_", " "), + nutrition_3m = str_replace_all(nutrition_3m, "_", " "), + community = str_split(q_k11, " - ", simplify = TRUE)[, 2], + q_k11 = str_split(q_k11, " - ", simplify = TRUE)[, 1], + q_7_1 = ifelse(q_7_1 == "Residents", "Host (Residents)", q_7_1), year = 2023 ) %>% select( @@ -156,13 +223,30 @@ raw_2023 <- safety_2, safety_3, safety_4, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_17_1, q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_2, q_7_2_1, q_7_4, q_7_6, q_7_7, aid_kind, q_7_9_1, q_7_9_2, q_7_9_3, issues_1, issues_2, issues_3, q_10_1, - q_11_1, nutrition_3m, q_15_1, barriers_healthcare, q_16_2, q_16_4, limit, - unex_events, event_hh_affected, year - ) + q_11_1, nutrition_3m, q_15_1, barr_health, q_16_2, q_16_4, limit, income, + event_1, event_2, event_3, affect_1, affect_2, affect_3, year, q_k11, community + ) %>% + filter( + q_7_1 != "IDPs in camps" + ) + + common_values <- intersect(msna_2022$q_k11, msna_2023$q_k11) + + sample_2022 <- msna_2022 %>% + filter(q_k11 %in% common_values) + + sample_2023 <- msna_2023 %>% + filter(q_k11 %in% common_values) # Data append ------------------------------------------------------------------ - msna <- bind_rows(msna_2022, msna_2023) + msna <- bind_rows(sample_2022, sample_2023) %>% + mutate( + q_8_5_2 = ifelse(q_8_5_2 == "Don't know / unsure", "Don't know", q_8_5_2), + q_8_5_3 = ifelse(q_8_5_3 == "Don't know / unsure", "Don't know", q_8_5_3), + q_17_3 = ifelse(q_17_3 %in% c("Don't know/unsure", "Don’t know/unsure"), NA, q_17_3), # Revisar este + year = as.character(year) + ) # Data quality ----------------------------------------------------------------- diff --git a/notebooks/msna/Codes/2_demographics.R b/notebooks/msna/Codes/2_demographics.R index 776ed54e..06cae5fa 100644 --- a/notebooks/msna/Codes/2_demographics.R +++ b/notebooks/msna/Codes/2_demographics.R @@ -26,10 +26,14 @@ for (i in unique_pop) { subset_data <- pop_2022 %>% filter(q_7_1 == i) - merged_data <- left_join(syria_shp, subset_data, by = "ADM3_PCODE") + pop_map <- left_join(syria_shp, subset_data, by = "ADM3_PCODE") + merged_data <- left_join(pop_map, earthquake, by = "ADM3_PCODE") %>% + mutate(earthquake = ifelse(is.na(earthquake), 0, 1)) pop_map <- ggplot(merged_data) + - geom_sf(aes(fill = pop)) + + geom_sf(aes(fill = pop), color = "black") + + geom_sf(data = merged_data[merged_data$earthquake == 1, ], + fill = "transparent", color = "red", size = 5, alpha = 0) + # Set alpha to 0 for transparency scale_fill_gradient(low = "lightblue", high = "darkblue", na.value = "white") + ggtitle(i) + theme_minimal() + @@ -55,10 +59,14 @@ for (i in unique_pop) { subset_data <- pop_2023 %>% filter(q_7_1 == i) - merged_data <- left_join(syria_shp, subset_data, by = "ADM3_PCODE") + pop_map <- left_join(syria_shp, subset_data, by = "ADM3_PCODE") + merged_data <- left_join(pop_map, earthquake, by = "ADM3_PCODE") %>% + mutate(earthquake = ifelse(is.na(earthquake), 0, 1)) pop_map <- ggplot(merged_data) + - geom_sf(aes(fill = pop)) + + geom_sf(aes(fill = pop), color = "black") + + geom_sf(data = merged_data[merged_data$earthquake == 1, ], + fill = "transparent", color = "red", size = 5, alpha = 0) + # Set alpha to 0 for transparency scale_fill_gradient(low = "lightblue", high = "darkblue", na.value = "white") + ggtitle(i) + theme_minimal() + diff --git a/notebooks/msna/Codes/3_1_conflict.R b/notebooks/msna/Codes/3_1_conflict.R index 10a8ac4f..ac7f0d23 100644 --- a/notebooks/msna/Codes/3_1_conflict.R +++ b/notebooks/msna/Codes/3_1_conflict.R @@ -6,17 +6,18 @@ # Presence of areas where women and girls feel unsafe -------------------------- -unsafety_2022 <- msna_2022 %>% - group_by(q_8_7, q_k10) %>% +unsafety <- msna %>% + group_by(q_8_7, year) %>% + filter(!is.na(q_8_7), q_8_7 != "Prefer not to answer") %>% mutate(ones = 1) %>% summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% - filter(!is.na(q_8_7), q_8_7 != "Prefer not to answer") + group_by(year) %>% + mutate(percentage = total / sum(total) * 100) %>% + mutate(percentage = round(percentage, 0)) %>% + ungroup() -unsafety_2022 <- transform(unsafety_2022, percentage = total / tapply(total, q_k10, sum)[q_k10]*100) %>% - mutate(percentage = round(percentage, 0)) - -bar_chart <- ggplot(unsafety_2022, aes(x = q_k10, y = percentage, fill = q_8_7)) + +bar_chart <- ggplot(unsafety, aes(x = year, y = percentage, fill = q_8_7)) + geom_bar(stat = "identity") + geom_text(aes(label = scales::percent(percentage, scale = 1)), # Add percentage labels position = position_stack(vjust = 0.5), # Adjust the vertical position of labels @@ -39,37 +40,59 @@ ggsave(here("Output", "bar_unsaf_girls.png"), bar_chart, width = 10, height = 6) # Main safety and security concerns in the past 3 months ----------------------- -safety_2022 <- msna_2022 %>% - select(id, starts_with("safety_"), q_k10) %>% +safety <- msna %>% + select(id, starts_with("safety_"), year) %>% pivot_longer(cols = starts_with("safety"), names_to = "safety_q", values_to = "safety_r") %>% - filter(!is.na(safety_r), safety_r != "Don't know/unsure", safety_r != "Prefer not to answer") %>% + filter(!is.na(safety_r), safety_r != "Don't know/unsure", safety_r != "Dont know", safety_r != "Prefer not to answer") %>% mutate(ones = 1, - safety_r = ifelse(safety_r %in% c("Discrimination on the basis of race, political beliefs, religion, class, age, sex, marital status (widow/divorced), disability, etc.", - "Discrimination of any sort", - "Other (please specify)", - "Physical and logistic constraints preventing mobility (roads damaged, buildings damaged, etc.)", - "Presence of UXO, IEDs, landmines, etc. around schools", - "Tensions between host communities and returnees in areas of return", - "Safety or security concerns related to displacement", - "Safety or security concerns related to conflict, i.e. including hostilities, destruction of property, threats, HH members injured/killed", + safety_r = ifelse(safety_r %in% c("Safety or security concerns related to conflict, i.e. including hostilities, destruction of property, threats, HH members injured/killed", + "Presence of UXO, IEDs, landmines, etc.", + "Mine UXOs", + "Fear of shelling airstrikes", + "Community tensions host IDP etc unsafe neighborhood due to crime", + "Being threatened with violence", + "Suffering from technology facilitated harrassment violence and blackmail", + "Suffering from physical harassment or violence not sexual", + "Suffering from sexual harassment or violence", "Threat of exploitation and abuse (including of a sexual nature) in the community", + "Tensions between host communities and returnees in areas of return", + "Suffering from verbal harassment", + "Being recruited by armed groups", + "Being killed", "Being robbed", "Being kidnapped", + "Being injured killed by an explosive hazard", + "Being exploited", "Being detained", "Exploitation due to disability", - "Presence of UXO, IEDs, landmines, etc."), - "Other", safety_r)) %>% - group_by(safety_r, q_k10) %>% + "Safety and security issues at home", + "Presence of UXO, IEDs, landmines, etc. around schools"), "Safety concerns related to conflict and violence", safety_r), + safety_r = ifelse(safety_r %in% c("Potential arrest violence at checkpoint", "Checkpoints", + "Arbitrary arrest or detention or risk of this happening", + "Arbitrary arrest, or detention, or risk of this happening"), "Arbitrary arrest, detention, checkpoints", safety_r), + safety_r = ifelse(safety_r %in% c("Other (please specify)", + "Shelter is unsafe lacks privacy separation doors risk of eviction", + "Shelter is unsafe at risk of collapse", + "Fear of drugs drug usage", + "Engage in hazardous work to generate more income", + "Being sent abroad to find work", + "Being forcibly married", + "Physical and logistic constraints preventing mobility (roads damaged, buildings damaged, etc.)", + "Discrimination on the basis of race political beliefs religion class age sex marital status widow divorced disability", + "Discrimination on the basis of race, political beliefs, religion, class, age, sex, marital status (widow/divorced), disability, etc."), "Other", safety_r), + safety_r = ifelse(safety_r == "Natural disaster earthquake", "Natural disaster (earthquake)", safety_r) + ) %>% + group_by(safety_r, year) %>% summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% - group_by(q_k10) %>% + group_by(year) %>% mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% ungroup() -bar_chart <- ggplot(safety_2022, aes(x = percentage, y = safety_r, fill = q_k10)) + +bar_chart <- ggplot(safety, aes(x = percentage, y = safety_r, fill = year)) + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + labs(title = "", x = "Percentage of Households", - y = "Need") + - scale_x_continuous(limits = c(0, max(safety_2022$percentage) + (max(safety_2022$percentage)/10))) + + y = "Security Concern") + + scale_x_continuous(limits = c(0, max(safety$percentage) + (max(safety$percentage)/10))) + scale_fill_manual(values = bar_colors) + theme_minimal() + theme( @@ -86,38 +109,26 @@ bar_chart <- ggplot(safety_2022, aes(x = percentage, y = safety_r, fill = q_k10) panel.grid.minor.x = element_blank() ) -ggsave(here("Output", "bar_sec.png"), bar_chart, width = 9, height = 6) +ggsave(here("Output", "bar_sec.png"), bar_chart, width = 10, height = 6) # Levels of stress experienced by a hh member ---------------------------------- - # 2022 - stress_2022 <- msna_2022 %>% - select(starts_with("q_8_5_"), q_7_1) %>% - mutate(stress = ifelse(q_8_5_0 == "Yes" | q_8_5_1 == "Yes" | q_8_5_2 == "Yes" | q_8_5_3 == "Yes", "Yes", "No"), - stress = ifelse((q_8_5_0 == "No" & is.na(stress)) | (q_8_5_1 == "No" & is.na(stress)) | (q_8_5_2 == "No" & is.na(stress)) | (q_8_5_3 == "No" & is.na(stress)), "No", stress), - ones = 1) %>% - filter(!is.na(stress)) %>% - group_by(stress, q_7_1) %>% - summarise(total = sum(ones, na.rm = TRUE), - .groups = 'drop') - # 2023 - stress_2023 <- msna_2023 %>% - select(starts_with("q_8_5_"), q_7_1) %>% +stress <- msna %>% mutate(stress = ifelse(q_8_5_0 == "Yes" | q_8_5_1 == "Yes" | q_8_5_2 == "Yes" | q_8_5_3 == "Yes", "Yes", "No"), stress = ifelse((q_8_5_0 == "No" & is.na(stress)) | (q_8_5_1 == "No" & is.na(stress)) | (q_8_5_2 == "No" & is.na(stress)) | (q_8_5_3 == "No" & is.na(stress)), "No", stress), ones = 1) %>% filter(!is.na(stress)) %>% - group_by(stress, q_7_1) %>% + group_by(stress, q_7_1, year) %>% summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') -unique_q_k10 <- unique(stress_2022$q_k10) +unique_year <- unique(stress$year) -for (value in unique_q_k10) { +for (value in unique_year) { - subset_data <- stress_2022 %>% - filter(q_k10 == value) %>% + subset_data <- stress %>% + filter(year == value) %>% transform(percentage = total / tapply(total, q_7_1, sum)[q_7_1]*100) %>% mutate(percentage = round(percentage, 0)) diff --git a/notebooks/msna/Codes/3_2_aid.R b/notebooks/msna/Codes/3_2_aid.R index 3fcd7e33..0113b7e8 100644 --- a/notebooks/msna/Codes/3_2_aid.R +++ b/notebooks/msna/Codes/3_2_aid.R @@ -6,8 +6,8 @@ # % of HH having received aid in the 3 months ---------------------------------- - aid_2022 <- msna_2022 %>% - group_by(q_k10, q_k9, q_7_1) %>% + aid <- msna %>% + group_by(year, q_k9, q_7_1) %>% summarise( per_aid_hh = mean(q_17_1 == "Yes", na.rm = TRUE) * 100, .groups = 'drop' @@ -16,40 +16,44 @@ subdis_code = str_split(q_k9, " - ", simplify = TRUE)[, 1], subdis_name = str_split(q_k9, " - ", simplify = TRUE)[, 2], ADM3_PCODE = subdis_code) %>% - select(ADM3_PCODE, subdis_code, subdis_name, q_k10, per_aid_hh, q_7_1) + select(ADM3_PCODE, subdis_code, subdis_name, year, per_aid_hh, q_7_1) - unique_q_k10 <- unique(aid_2022$q_k10) - unique_pop <- unique(pop_2022$q_7_1) + unique_year <- unique(aid$year) + unique_pop <- unique(aid$q_7_1) for (i in unique_pop) { - for (j in unique_q_k10) { + for (j in unique_year) { - subset_data <- aid_2022 %>% filter(q_7_1 == i, q_k10 == j) - merged_data <- left_join(syria_shp, subset_data, by = "ADM3_PCODE") + subset_data <- aid %>% filter(q_7_1 == i, year == j) + pop_map <- left_join(syria_shp, subset_data, by = "ADM3_PCODE") + merged_data <- left_join(pop_map, earthquake, by = "ADM3_PCODE") %>% + mutate(earthquake = ifelse(is.na(earthquake), 0, 1)) pop_map <- ggplot(merged_data) + - geom_sf(aes(fill = per_aid_hh)) + + geom_sf(aes(fill = per_aid_hh), color = "black") + + geom_sf(data = merged_data[merged_data$earthquake == 1, ], + fill = "transparent", color = "red", size = 5, alpha = 0) + # Set alpha to 0 for transparency scale_fill_gradient(low = "lightblue", high = "darkblue", na.value = "white") + ggtitle(i) + theme_minimal() + theme(legend.position = "right") + - labs(fill = "Percentage") + labs(fill = "Percentage of HHs") - ggsave(here("Output", "2022", paste0("/aid_", i, "_", j, ".png")), plot = pop_map, width = 7, height = 6, units = "in", dpi = 300) + ggsave(here("Output", paste0("/aid_", i, "_", j, ".png")), plot = pop_map, width = 7, height = 6, units = "in", dpi = 300) } } # Aid satisfaction ------------------------------------------------------------- -aid_2022 <- msna_2022 %>% +aid <- msna %>% filter(!is.na(q_17_3)) -unique_q_k10 <- unique(msna_2022$q_k10) +unique_year <- unique(aid$year) -for (value in unique_q_k10) { - subset_data <- aid_2022 %>% - filter(q_k10 == value) %>% +for (value in unique_year) { + subset_data <- aid %>% + filter(year == value) %>% group_by(q_7_1, q_17_3) %>% summarise(n = n()) %>% mutate(percentage = round(n / sum(n) * 100, 1)) %>% @@ -57,70 +61,75 @@ for (value in unique_q_k10) { pos = percentage/2 + lead(csum, 1), pos = if_else(is.na(pos), percentage/2, pos)) -pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_17_3))) + - geom_bar(stat = "identity", width = 1, color = "white") + - coord_polar(theta = "y") + - geom_label_repel(data = subset_data, - aes(y = pos, label = paste0(percentage, "%")), - size = 3, nudge_x = 0.7, show.legend = FALSE) + - labs(fill = "") + - theme_minimal() + - theme(legend.position = "right", - plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), - plot.caption = element_text(hjust = 0.5, size = 10), - axis.text = element_blank(), - axis.title = element_blank(), - panel.grid = element_blank()) + - scale_fill_manual(values = pie_colors) + - facet_wrap(~q_7_1, ncol = 3) + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_17_3))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) ggsave(here("Output", paste0("pie_aid_sat_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) } # Priority needs --------------------------------------------------------------- -needs_2022 <- msna_2022 %>% - select(id, q_7_1, q_16_1_1, q_k10) %>% +needs <- msna %>% + select(id, q_7_1, q_16_1_1, year) %>% rename(need = q_16_1_1) %>% filter(need != "All needs are met") %>% mutate(id = id, ones = 1, - need = ifelse(need == "Shelter assistance (emergency shelter provision, shelter repairs, rent subsidies)", "Shelter assistance", need), - need = ifelse(need %in% c("Other (specify)", - "Access to community centers and safe spaces for women and girls", - "Reintegration services", "GBV post services", - "Risk awareness and clearance (Mine Action)", - "Technical and vocational training", - "No other reasons", - "Don't know/unsure", - "Waste disposal", - "Access to safe water", - "WASH services (unloading service, toilet, handbasin, associated connections/sewage system)", - "Phone/data/communication", - "Education services", - "Electricity provision", - "Disability-specific needs (medical equipment, medicine, services)", + need = ifelse(need %in% c("Dont know", "Don't know/unsure", "Prefer not to answer"), NA, need), + need = ifelse(need %in% c("Food", "Nutrition nutrition services"), "Food/nutrition", need), + need = ifelse(need %in% c("Access to safe water", "Electricity provisio internet", + "Electricity provision", "Sanitation", "Waste disposal"), "WASH and electricity", need), + need = ifelse(need %in% c("Access to community centers and safe spaces for women and girls", + "NFI items", "NFI items (e.g. clothing, blankets, cooking material, sanitation items, fuel and school equipment)", + "Shelter assistance", "Shelter assistance (emergency shelter provision, shelter repairs, rent subsidies)"), "Shelter and NFI items", need), + need = ifelse(need %in% c("Disability-specific needs (medical equipment, medicine, services)", + "Disability specific needs medical equipment medicine services assistive devices to support access to work or education", "Health services", "Medicine", - "Mental health and psychosocial support services (e.g. structured group activities in a safe space, invididual or group counseling, etc.)"), "Other", need), - need = ifelse(need %in% c("NFI items (e.g. clothing, blankets, cooking material, sanitation items, fuel and school equipment)", "Shelter assistance"), "Shelter assistance, NFI items", need), - need = ifelse(need %in% c("Legal advice including civil documentation and Housing, Land and Property", - "Livelihood opportunities/inability to work"), "Legal advice and documentation", need)) %>% - group_by(need, q_7_1, q_k10) %>% + "Mental health and psychosocial support services", + "Mental health and psychosocial support services (e.g. structured group activities in a safe space, invididual or group counseling, etc.)"), "Health and medical services", need), + need = ifelse(need %in% c("Education services", "Formal education", + "GBV post services", "Legal advice including civil documentation and Housing Land and Property", + "Legal advice including civil documentation and Housing, Land and Property", + "Livelihood opportunities ability to work", + "Livelihood opportunities/inability to work", + "Non formal education", + "Phone data communication", + "Phone/data/communication", + "Reintegration services", "Risk awareness and clearance (Mine Action)", + "Risk awareness and clearance Mine Action", + "Technical and vocational training", + "Technical and vocational trainings"), "Other", need) + ) %>% + group_by(need, q_7_1, year) %>% summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% filter(!is.na(need)) %>% - group_by(q_7_1, q_k10) %>% + group_by(q_7_1, year) %>% mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% ungroup() -unique_q_k10 <- unique(safety_2022$q_k10) +unique_year <- unique(needs$year) -for (value in unique_q_k10) { - plot_data <- filter(needs_2022, q_k10 == value) +for (value in unique_year) { + plot_data <- filter(needs, year == value) bar_chart <- ggplot(plot_data, aes(x = percentage, y = need, fill = q_7_1)) + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + - labs(title = "", + labs(title = value, x = "Percentage of Households", y = "Need") + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + @@ -140,7 +149,7 @@ for (value in unique_q_k10) { panel.grid.minor.x = element_blank() ) - ggsave(here("Output", paste0("/bar_need", gsub("/", "_", value), ".png")), bar_chart, width = 9, height = 6) + ggsave(here("Output", paste0("/bar_need", gsub("/", "_", value), ".png")), bar_chart, width = 7.5, height = 6) } # GoS-issued documentation ----------------------------------------------------- diff --git a/notebooks/msna/Codes/3_3_displacement.R b/notebooks/msna/Codes/3_3_displacement.R index 037ef0c8..96307cc1 100644 --- a/notebooks/msna/Codes/3_3_displacement.R +++ b/notebooks/msna/Codes/3_3_displacement.R @@ -7,18 +7,19 @@ # If host population, have you ever been displaced? ---------------------------- # Title: Percentage of host population households that have been displaced -displaced_2022 <- msna_2022 %>% +displaced <- msna %>% filter(!is.na(q_7_2)) %>% - count(q_7_2) %>% - mutate(percentage = round(n / sum(n) * 100, 1)) %>% - mutate(csum = rev(cumsum(rev(percentage))), - pos = percentage/2 + lead(csum, 1), - pos = if_else(is.na(pos), percentage/2, pos)) - - pie_chart <- ggplot(displaced_2022, aes(x = "", y = percentage, fill = fct_inorder(q_7_2))) + + group_by(year, q_7_2) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(displaced, aes(x = "", y = percentage, fill = fct_inorder(q_7_2))) + geom_bar(stat = "identity", width = 1, color = "white") + coord_polar(theta = "y") + - geom_label_repel(data = displaced_2022, + geom_label_repel(data = displaced, aes(y = pos, label = paste0(percentage, "%")), size = 3, nudge_x = 0.7, show.legend = FALSE) + labs(fill = "") + @@ -29,48 +30,50 @@ displaced_2022 <- msna_2022 %>% axis.text = element_blank(), axis.title = element_blank(), panel.grid = element_blank()) + - scale_fill_manual(values = pie_colors) + scale_fill_manual(values = pie_colors) + + facet_wrap(~year, ncol = 2) - ggsave(here("Output", "pie_hh_dis.png"), plot = pie_chart, width = 6, height = 6, units = "in", dpi = 300) + ggsave(here("Output", "pie_hh_dis.png"), plot = pie_chart, width = 8, height = 6, units = "in", dpi = 300) # Host HHs coming back to their current location after being displaced --------- -host_date_2022 <- msna_2022 %>% - filter(!is.na(q_7_2_1)) %>% - group_by(q_7_2_1) %>% - summarise(obs = cumsum(n())) - -time_chart <- host_date_2022 %>% - ggplot(aes(x = q_7_2_1, y = obs)) + - geom_line(color = "steelblue", size = 1.2) + - scale_y_continuous(limits = c(0, 250), expand = c(0, 0)) + - labs(title = "", - x = "Date", - y = "Households") + - theme_minimal() + - theme(axis.text.x = element_text(angle = 45, hjust = 1), - axis.title = element_text(face = "bold"), - plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), - panel.grid.major = element_line(color = "lightgray", linetype = "dashed"), - panel.grid.minor = element_blank(), - axis.line = element_line(color = "black")) + host_date <- msna %>% + filter(!is.na(q_7_2_1)) %>% + group_by(year, q_7_2_1) %>% + summarise(obs = cumsum(n())) -ggsave(here("Output", paste0("time_host_ret", gsub(" ", "_", value), ".png")), plot = time_chart, width = 10, height = 6, units = "in", dpi = 300) + time_chart <- host_date %>% + ggplot(aes(x = q_7_2_1, y = obs, color = year)) + + geom_line(size = 1.2) + + scale_y_continuous(limits = c(0, 100), expand = c(0, 0)) + + labs(title = "", + x = "Date", + y = "Households") + + theme_minimal() + + theme(axis.text.x = element_text(angle = 45, hjust = 1), + axis.title = element_text(face = "bold"), + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + panel.grid.major = element_line(color = "lightgray", linetype = "dashed"), + panel.grid.minor = element_blank(), + axis.line = element_line(color = "black")) + +ggsave(here("Output", "time_host_ret.png"), plot = time_chart, width = 10, height = 6, units = "in", dpi = 300) # Where did the hh reside prior to returning to their original community ------- -returnee_2022 <- msna_2022 %>% +returnee <- msna %>% filter(!is.na(q_7_4)) %>% - count(q_7_4) %>% + group_by(year, q_7_4) %>% + summarise(n = n()) %>% mutate(percentage = round(n / sum(n) * 100, 1)) %>% mutate(csum = rev(cumsum(rev(percentage))), pos = percentage/2 + lead(csum, 1), pos = if_else(is.na(pos), percentage/2, pos)) - pie_chart <- ggplot(returnee_2022, aes(x = "", y = percentage, fill = fct_inorder(q_7_4))) + + pie_chart <- ggplot(returnee, aes(x = "", y = percentage, fill = fct_inorder(q_7_4))) + geom_bar(stat = "identity", width = 1, color = "white") + coord_polar(theta = "y") + - geom_label_repel(data = returnee_2022, + geom_label_repel(data = returnee, aes(y = pos, label = paste0(percentage, "%")), size = 3, nudge_x = 0.7, show.legend = FALSE) + labs(fill = "") + @@ -81,85 +84,85 @@ returnee_2022 <- msna_2022 %>% axis.text = element_blank(), axis.title = element_blank(), panel.grid = element_blank()) + - scale_fill_manual(values = pie_colors) + scale_fill_manual(values = pie_colors) + + facet_wrap(~year, ncol = 2) - ggsave(here("Output", "pie_returnee.png"), plot = pie_chart, width = 6, height = 6, units = "in", dpi = 300) + ggsave(here("Output", "pie_returnee.png"), plot = pie_chart, width = 8, height = 6, units = "in", dpi = 300) # IDP HHs arriving to their current location ----------------------------------- -idp_date_2022 <- msna_2022 %>% +idp_date <- msna %>% filter(!is.na(q_7_6)) %>% - group_by(q_7_6) %>% + group_by(year, q_7_6) %>% summarise(obs = cumsum(n())) -time_chart <- idp_date_2022 %>% - ggplot(aes(x = q_7_6, y = obs)) + - geom_line(color = "steelblue", size = 1.2) + - scale_y_continuous(limits = c(0, 250), expand = c(0, 0)) + - labs(title = "", - x = "Date", - y = "Households") + - theme_minimal() + - theme(axis.text.x = element_text(angle = 45, hjust = 1), - axis.title = element_text(face = "bold"), - plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), - panel.grid.major = element_line(color = "lightgray", linetype = "dashed"), - panel.grid.minor = element_blank(), - axis.line = element_line(color = "black")) + time_chart <- idp_date %>% + ggplot(aes(x = q_7_6, y = obs, color = year)) + + geom_line(size = 1.2) + + scale_y_continuous(limits = c(0, 100), expand = c(0, 0)) + + labs(title = "", + x = "Date", + y = "Households") + + theme_minimal() + + theme(axis.text.x = element_text(angle = 45, hjust = 1), + axis.title = element_text(face = "bold"), + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + panel.grid.major = element_line(color = "lightgray", linetype = "dashed"), + panel.grid.minor = element_blank(), + axis.line = element_line(color = "black")) -ggsave(here("Output", paste0("time_idp_arr", gsub(" ", "_", value), ".png")), plot = time_chart, width = 10, height = 6, units = "in", dpi = 300) +ggsave(here("Output", "time_idp_arr.png"), plot = time_chart, width = 10, height = 6, units = "in", dpi = 300) # For IDPs, how many times have you and your HH been displaced since 2011? ----- # Title: Times IDP households have been displaced since 2011 -unique_q_k10 <- unique(msna_2022$q_k10) + subset_data <- msna %>% + filter(!is.na(q_7_7)) -for (value in unique_q_k10) { - subset_data <- msna_2022 %>% - filter(!is.na(q_7_7), q_k10 == value) - - hist_chart <- ggplot(subset_data, aes(x = q_7_7)) + - geom_histogram(binwidth = 1, fill = "skyblue", color = "darkblue", alpha = 0.7) + - labs(title = value, x = "Number of Times", y = "Frequency") + + hist_chart <- ggplot(subset_data, aes(x = q_7_7, fill = year)) + + geom_histogram(binwidth = 1, position = "identity", color = "white", alpha = 0.4) + + labs(title = "", x = "Number of Times", y = "Frequency") + theme_minimal() + - theme(plot.title = element_text(hjust = 0.5)) # Centering the title + theme(plot.title = element_text(hjust = 0.5)) - ggsave(here("Output", paste0("hist_time_disp", gsub(" ", "_", value), ".png")), plot = hist_chart, width = 6, height = 7, units = "in", dpi = 300) -} + ggsave(here("Output", "hist_time_disp.png"), plot = hist_chart, width = 9, height = 6, units = "in", dpi = 300) # Main reasons for displacement for IPS households ----------------------------- -push_2022 <- msna_2022 %>% - select(id, q_k10, q_7_9_1) %>% +push <- msna %>% + select(id, year, q_7_9_1) %>% rename( push = q_7_9_1 ) %>% mutate(id = id, ones = 1, - push = ifelse(push %in% c("Insufficient/no availability of public services in last place lived (health, education, markets, WASH, etc.)", - "Other (specify)", + push = ifelse(push == "Worse security situation in last place lived", "Security reasons", push), + push = ifelse(push %in% c("Pursuit of better economic situation lower prices livelihood opportunities", + "Worse economic situation last place lived", + "Worse livelihood opportunities in last placce lived", + "Unacceptable living conditions (lack of water, power, sewage, privacy/overcrowding, heating, safety, etc.) in last place lived"), "Economic and livelihood reasons", push), + push = ifelse(push %in% c("Family reasons to reunite with family or to be close to family", "Insufficient/no availability of humanitarian assistance in last place lived", - "Unacceptable living conditions (lack of water, power, sewage, privacy/overcrowding, heating, safety, etc.) in last place lived", - "Separated from my family in last place lived"), "Other", push), - push = ifelse(push == "Worse economic situation last place lived", "Worse economic situation", push), - push = ifelse(push == "Worse livelihood opportunities in last placce lived", "Worse livelihood opportunities", push), - push = ifelse(push == "Worse security situation in last place lived", "Worse security situation", push), - ) %>% - group_by(push, q_k10) %>% + "Insufficient/no availability of public services in last place lived (health, education, markets, WASH, etc.)", + "Pursuit of better public services", + "Separated from my family in last place lived", + "Pursuit of humanitarian assistance"), "Other", push) + ) %>% + group_by(push, year) %>% summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% filter(!is.na(push)) %>% - group_by(q_k10) %>% + group_by(year) %>% mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% ungroup() -bar_chart <- ggplot(push_2022, aes(x = percentage, y = push, fill = q_k10)) + +bar_chart <- ggplot(push, aes(x = percentage, y = push, fill = year)) + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + labs(title = "", x = "Percentage of Households", y = "Push Factor") + - scale_x_continuous(limits = c(0, max(push_2022$percentage) + (max(push_2022$percentage)/10))) + + scale_x_continuous(limits = c(0, max(push$percentage) + (max(push$percentage)/10))) + scale_fill_manual(values = bar_colors) + theme_minimal() + theme( @@ -180,8 +183,8 @@ ggsave(here("Output", "bar_push.png"), bar_chart, width = 9, height = 6) # Type of shelter / housing the hh currently reside (by population type) ------- -type_hh_2022 <- msna_2022 %>% - select(id, q_7_1, q_10_1, q_k10) %>% +type_hh <- msna %>% + select(id, q_7_1, q_10_1, year) %>% mutate(ones = 1, q_10_1 = ifelse(q_10_1 %in% c("Other (specify)", "Substandard building (factory, farm, shop)", @@ -191,11 +194,11 @@ type_hh_2022 <- msna_2022 %>% "Concrete block shelter", "House/ apartment (unfinished)"), "Other", q_10_1)) -unique_q_k10 <- unique(type_hh_2022$q_k10) +unique_year <- unique(type_hh$year) -for (value in unique_q_k10) { - subset_data <- type_hh_2022 %>% - filter(q_k10 == value) %>% +for (value in unique_year) { + subset_data <- type_hh %>% + filter(year == value) %>% group_by(q_7_1, q_10_1) %>% summarise(n = n()) %>% mutate(percentage = round(n / sum(n) * 100, 1)) %>% @@ -225,40 +228,48 @@ for (value in unique_q_k10) { # Adequacy issues in the hh shelter -------------------------------------------- -issues_2022 <- msna_2022 %>% - select(id, starts_with("issues_"), q_k10, q_7_1) %>% +issues <- msna %>% + select(id, starts_with("issues_"), year, q_7_1) %>% pivot_longer(cols = starts_with("issues"), names_to = "issues_q", values_to = "issues_r") %>% filter(!is.na(issues_r)) %>% mutate(ones = 1, issues_r = ifelse(issues_r %in% c("Lack of electricity/ lighting (fixtures/ associated connections)", "Lack of water (fixtures, associated connections)", - "Lack or defective sanitation (toilet, handbasin, associated connections/sewage system)"), "Lack of WASH", issues_r), + "Lack domestic lighting lamps and wiring", + "Lack of or defective sanitation toilet handbasin and plumbing", + "Lack of water taps basins and plumbing", + "Lack or defective sanitation (toilet, handbasin, associated connections/sewage system)"), + "Lack of WASH or electricity", issues_r), issues_r = ifelse(issues_r == "None (cannot be selected with any other option)", "None", issues_r), + issues_r = ifelse(issues_r == "Lack of insulation from heat cold", "Lack of insulation from heat, cold", issues_r), issues_r = ifelse(issues_r %in% c("Lack of privacy (space/ partitions, doors)", "Unable to lock home securely"), "Lack of privacy or security", issues_r), issues_r = ifelse(issues_r %in% c("Leakage from roof/ ceiling", + "Leakage from roof ceiling", "Windows/ doors not sealed", - "Poor facilities for persons with specific needs (PwSN) i.e. unable to access due to physical/ health condition"), "Other", issues_r), - issues_r = ifelse(issues_r == "Other (please specify)", NA, issues_r) + "Windows doors not sealed", + "Poor facilities for persons with specific needs (PwSN) i.e. unable to access due to physical/ health condition"), + "Infraestructure issues", issues_r), + issues_r = ifelse(issues_r %in% c("Other (please specify)", "Other"), NA, issues_r) ) %>% - group_by(issues_r, q_k10, q_7_1) %>% + group_by(issues_r, year, q_7_1) %>% summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% filter(!is.na(issues_r)) %>% - group_by(q_7_1, q_k10) %>% + group_by(q_7_1, year) %>% mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% ungroup() -unique_q_k10 <- unique(issues_2022$q_k10) +unique_year <- unique(needs$year) -for (value in unique_q_k10) { - plot_data <- filter(issues_2022, q_k10 == value) +for (value in unique_year) { + plot_data <- filter(issues, year == value) bar_chart <- ggplot(plot_data, aes(x = percentage, y = issues_r, fill = q_7_1)) + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + - labs(title = "", + labs(title = value, x = "Percentage of Households", - y = "Adequacy Issues") + + y = "Adequacy Issue") + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + scale_fill_manual(values = bar_colors) + theme_minimal() + @@ -276,5 +287,5 @@ for (value in unique_q_k10) { panel.grid.minor.x = element_blank() ) - ggsave(here("Output", paste0("bar_issue_", gsub(" ", "_", value), ".png")), bar_chart, width = 9, height = 6) + ggsave(here("Output", paste0("bar_issue_", gsub(" ", "_", value), ".png")), bar_chart, width = 7.5, height = 6) } \ No newline at end of file diff --git a/notebooks/msna/Codes/3_4_hh_welfare.R b/notebooks/msna/Codes/3_4_hh_welfare.R index 58a98c42..61ec9413 100644 --- a/notebooks/msna/Codes/3_4_hh_welfare.R +++ b/notebooks/msna/Codes/3_4_hh_welfare.R @@ -6,14 +6,15 @@ # % of HHs by number of hours of access to electricity ------------------------- -electr_2022 <- msna_2022 %>% - filter(!is.na(q_15_1)) +electr <- msna %>% + filter(!is.na(q_15_1)) %>% + mutate(q_15_1 = factor(q_15_1, levels = c("0 hours per day", "1-2 hours per day", "3-8 hours per day", "9-15 hours per day", "16+ hours per day"))) -unique_q_k10 <- unique(wat_2022$q_k10) +unique_year <- unique(electr$year) -for (value in unique_q_k10) { - subset_data <- electr_2022 %>% - filter(q_k10 == value) %>% +for (value in unique_year) { + subset_data <- electr %>% + filter(year == value) %>% group_by(q_7_1, q_15_1) %>% summarise(n = n()) %>% mutate(percentage = round(n / sum(n) * 100, 1)) %>% @@ -41,17 +42,55 @@ for (value in unique_q_k10) { ggsave(here("Output", paste0("pie_elec_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) } + +# % of HHs reported access to nutrition services in past 3m (2023) ------------- + +nutri <- sample_2023 %>% + mutate( + nutrition_3m = ifelse(nutrition_3m == "Dont know", NA, + ifelse(nutrition_3m == "Yes", "Yes", "No") + ) + ) %>% + filter(!is.na(nutrition_3m)) + + subset_data <- nutri %>% + group_by(q_7_1, nutrition_3m) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(nutrition_3m))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors4) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", "pie_nut_2023.png"), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) + # % of households reporting having had sufficient water for drinking ----------- -wat_2022 <- msna_2022 %>% +wat <- msna %>% filter(!is.na(q_11_1)) %>% mutate() -unique_q_k10 <- unique(wat_2022$q_k10) +unique_year <- unique(wat$year) -for (value in unique_q_k10) { - subset_data <- wat_2022 %>% - filter(q_k10 == value) %>% +for (value in unique_year) { + subset_data <- wat %>% + filter(year == value) %>% group_by(q_7_1, q_11_1) %>% summarise(n = n()) %>% mutate(percentage = round(n / sum(n) * 100, 1)) %>% @@ -79,15 +118,72 @@ for (value in unique_q_k10) { ggsave(here("Output", paste0("pie_wat_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) } +# Main reason limiting household’s ability to access healthcare (2023) --------- + +barr <- sample_2023 %>% + select(id, year, barr_health, q_7_1) %>% + mutate(id = id, + ones = 1, + barr_health = ifelse(barr_health %in% c("Turned away at the health facility", + "Poor water sanitation and hygiene conditions in health care facilities lack of latrines access to clean water etc", + "Not trained staff at health facility", + "Not safe insecurity while travelling to health facility", + "Not enough staff at health facility", + "No means of transport", + "Lack of female staff at facility", + "Judgemntal attitude or negative treatment", + "Health facility is too far away", + "Fear or distrust of health workers examination or treatment", + "Disability prevents access to health facility", + "Did not receive correct medications", + "No functional health facility nearby"), "Other", barr_health), + barr_health = ifelse(barr_health %in% c("Could not afford cost of consultation", + "Could not afford cost of treatment", + "Could not afford transportation to health facility"), "Could not afford related costs", barr_health) + ) %>% + filter(!is.na(barr_health), barr_health != "Dont know", barr_health != "Prefer not to answer") %>% + group_by(barr_health, year, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + group_by(q_7_1, year) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + bar_chart <- ggplot(barr, aes(x = percentage, y = barr_health, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = , + x = "Percentage of Households", + y = "Limitation") + + scale_x_continuous(limits = c(0, max(barr$percentage) + (max(barr$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", "/bar_barr_2023.png"), bar_chart, width = 9, height = 6) + # % of HHs by ability to meet the basic needs ---------------------------------- -bn_2022 <- msna_2022 %>% +bn <- msna %>% filter(!is.na(q_16_2)) -unique_q_k10 <- unique(bn_2022$q_k10) -for (value in unique_q_k10) { - subset_data <- bn_2022 %>% - filter(q_k10 == value) %>% +unique_year <- unique(bn$year) + +for (value in unique_year) { + subset_data <- bn %>% + filter(year == value) %>% group_by(q_7_1, q_16_2) %>% summarise(n = n()) %>% mutate(percentage = round(n / sum(n) * 100, 1)) %>% @@ -117,8 +213,8 @@ for (value in unique_q_k10) { # Main reason limiting household’s ability to meet their basic needs ----------- -limits_2022 <- msna_2022 %>% - select(id, q_k10, limit, q_7_1) %>% +limits <- msna %>% + select(id, year, limit, q_7_1) %>% mutate(id = id, ones = 1, limit = ifelse(limit %in% c("Other (please specify)", @@ -129,25 +225,35 @@ limits_2022 <- msna_2022 %>% "Disability of one or more members in the HH", "Issues related to lack of civil documentation", "HH no longer receiving assistance", - "Loss of remittances"), "Other", limit) + "Loss of remittances", + "Restrictions on movement", + "Unavailability of items medicines bread water fuel etc", + "Direct losses and or displacement due to the earthquakes"), "Other", limit), + limit = ifelse(limit %in% c("Death absence of primary breadwinner", + "Disability illness of one or more members in the HH leading to bigger expenses", + "Expensive services health education electricity etc", + "Loss of remittances general", + "Eviction housing unable to pay rent", + "Loss of remittances value of money received has decreased no modality to receive"), "Insufficient/lack of income", limit), + limit = ifelse(limit == "Unemployment loss of job", "Unemployment/loss of job", limit) ) %>% filter(!is.na(limit), limit != "Prefer not to answer", limit != "No other Reasons") %>% - group_by(limit, q_k10, q_7_1) %>% + group_by(limit, year, q_7_1) %>% summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% - group_by(q_7_1, q_k10) %>% + group_by(q_7_1, year) %>% mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% ungroup() -unique_q_k10 <- unique(safety_2022$q_k10) +unique_year <- unique(limits$year) -for (value in unique_q_k10) { - plot_data <- filter(limits_2022, q_k10 == value) +for (value in unique_year) { + plot_data <- filter(limits, year == value) bar_chart <- ggplot(plot_data, aes(x = percentage, y = limit, fill = q_7_1)) + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + - labs(title = "", + labs(title = value, x = "Percentage of Households", y = "Limitation") + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + @@ -167,23 +273,19 @@ for (value in unique_q_k10) { panel.grid.minor.x = element_blank() ) - ggsave(here("Output", paste0("/bar_lim", gsub("/", "_", value), ".png")), bar_chart, width = 9, height = 6) + ggsave(here("Output", paste0("/bar_lim", gsub("/", "_", value), ".png")), bar_chart, width = 7.5, height = 6) } -# Access to healthcare --------------------------------------------------------- +# Access to healthcare (Only 2022) --------------------------------------------- -health_2022 <- msna_2022 %>% +health_2022 <- sample_2022 %>% filter(!is.na(q_9_4_1)) %>% mutate( health = ifelse(q_9_4_1 > 0, "Not all members got access", "All members got access") ) %>% - select(health, q_k10, q_7_1) + select(health, q_7_1) -unique_q_k10 <- unique(health_2022$q_k10) - -for (value in unique_q_k10) { subset_data <- health_2022 %>% - filter(q_k10 == value) %>% group_by(q_7_1, health) %>% summarise(n = n()) %>% mutate(percentage = round(n / sum(n) * 100, 1)) %>% @@ -208,25 +310,27 @@ for (value in unique_q_k10) { scale_fill_manual(values = pie_colors) + facet_wrap(~q_7_1, ncol = 3) - ggsave(here("Output", paste0("pie_health_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) -} + ggsave(here("Output", "pie_health_2022.png"), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) # Household income over the last 3 months -------------------------------------- -income_2022 <- msna_2022 %>% - select(income, q_k10, q_16_4, q_7_1) %>% - filter(q_16_4 == "Yes") - -unique_q_k10 <- unique(income_2022$q_k10) +income <- msna %>% + select(income, year, q_16_4, q_7_1) %>% + filter(q_16_4 == "Yes") + +unique_year <- unique(income$year) -for (value in unique_q_k10) { +for (value in unique_year) { - subset_data <- income_2022 %>% - filter(q_k10 == value) + subset_data <- income %>% + filter(year == value) %>% + mutate( + income = ifelse(income > quantile(income, 0.95, na.rm = TRUE), NA, income) + ) hist_chart <- ggplot(subset_data, aes(x = factor(q_7_1), y = income)) + geom_boxplot(fill = "lightblue", color = "blue") + - labs(title = "", + labs(title = "Outliers treated at 95%", x = "Population type", y = "Syrian Pounds (SYP)") + theme_minimal() + @@ -244,6 +348,5 @@ for (value in unique_q_k10) { panel.grid.minor.x = element_blank() ) - ggsave(here("Output", paste0("box_income", gsub(" ", "_", value), ".png")), plot = hist_chart, width = 9, height = 6, units = "in", dpi = 300) - + ggsave(here("Output", paste0("box_income", gsub(" ", "_", value), ".png")), plot = hist_chart, width = 7, height = 6, units = "in", dpi = 300) } \ No newline at end of file From 65932611592d4b87b076c4f29a02ff2c440dd835 Mon Sep 17 00:00:00 2001 From: ivilaco Date: Sat, 2 Dec 2023 15:29:53 -0500 Subject: [PATCH 4/5] Data update --- notebooks/msna/Codes/1_cleaning.R | 494 ++++++++++++++------------ notebooks/msna/Codes/3_4_hh_welfare.R | 6 +- notebooks/msna/Codes/maps.do | 6 +- 3 files changed, 277 insertions(+), 229 deletions(-) diff --git a/notebooks/msna/Codes/1_cleaning.R b/notebooks/msna/Codes/1_cleaning.R index f9116807..8d1662b2 100644 --- a/notebooks/msna/Codes/1_cleaning.R +++ b/notebooks/msna/Codes/1_cleaning.R @@ -6,49 +6,49 @@ # Import raw data -------------------------------------------------------------- - raw_2022 <- - read_xlsx( - here( - "Data", - "Raw", - "2022-09-06_SYR_MSNA2022_dataset_HHs.xlsx" - ), - sheet = "Dataset - households" - ) - - raw_2023 <- - read_xlsx( - here( - "Data", - "Raw", - "MSNA2023_dataset.xlsx" - ), - sheet = "Dataset - households" +raw_2022 <- + read_xlsx( + here( + "Data", + "Raw", + "2022-09-06_SYR_MSNA2022_dataset_HHs.xlsx" + ), + sheet = "Dataset - households" + ) + +raw_2023 <- + read_xlsx( + here( + "Data", + "Raw", + "MSNA2023_dataset.xlsx" + ), + sheet = "Dataset - households" + ) + +raw_e <- + read_xlsx( + here( + "Data", + "Raw", + "syria-earthquake-impact-20-march-2023.xlsx" + ), + sheet = "DATASET" + ) + +syria_shp <- + st_read( + here( + "Data", + "Raw", + "syr_admbnda_adm3_uncs_unocha_20201217-polygon.shp" ) - - raw_e <- - read_xlsx( - here( - "Data", - "Raw", - "syria-earthquake-impact-20-march-2023.xlsx" - ), - sheet = "DATASET" - ) - - syria_shp <- - st_read( - here( - "Data", - "Raw", - "syr_admbnda_adm3_uncs_unocha_20201217-polygon.shp" - ) - ) + ) # Data preparation ------------------------------------------------------------- - # Earthquake - earthquake <- raw_e %>% +# Earthquake +earthquake <- raw_e %>% select(ADM3_EN, ADM3_PCODE, ADM4_EN, ADM4_PCODE, casualties, injuries, des_houses, damag_houses) %>% group_by(ADM3_PCODE) %>% @@ -58,205 +58,251 @@ total_des_houses = sum(des_houses, na.rm = TRUE), total_damag_houses = sum(damag_houses, na.rm = TRUE) ) %>% - mutate( - earthquake = 1 - ) + mutate( + earthquake = 1 + ) - # 2022 - msna_2022 <- - raw_2022 %>% - filter(q_k10 != "Neighborhood") %>% - separate( - q_16_8, - into = c("safety_1", "safety_2", "safety_3", "safety_4", "safety_5"), - sep = "; " - ) %>% +# 2022 +msna_2022 <- + raw_2022 %>% + filter(q_k10 != "Neighborhood") %>% + separate( + q_16_8, + into = c("safety_1", "safety_2", "safety_3", "safety_4", "safety_5"), + sep = "; " + ) %>% separate( q_10_4, into = c("issues_1", "issues_2", "issues_3", "issues_4", "issues_5"), sep = "; " ) %>% - mutate(q_17_1 = ifelse(q_17_1 %in% c("Don't know / unsure", "Prefer not to answer"), NA, q_17_1), - q_17_3 = ifelse(q_17_3 == "Prefer to not answer", NA, q_17_3), - q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), - q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", - "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), - q_7_1 = ifelse(q_7_1 == "Internally displaced person (IDP)" & q_k10 == "Camp", "IDPs in camps", q_7_1), - q_7_1 = ifelse(q_7_1 == "Internally displaced person (IDP)" & q_k10 != "Camp", "IDPs out of camps", q_7_1), - q_7_1 = ifelse(q_7_1 == "Host population", "Host (Residents)", q_7_1), - q_7_1 = ifelse(q_7_1 == "Returnee (returned in 2022)", "Returnees (2022)", q_7_1), - q_r3 = ifelse(q_r3 == "Widow / Widower", "Widowed", q_r3), - q_8_7 = ifelse(q_8_7 == "Don't know / unsure", "Don't know", q_8_7), - q_8_5_0 = ifelse(q_8_5_0 == "Don't know / unsure", "Don't know", q_8_5_0), - q_8_5_1 = ifelse(q_8_5_1 == "Don't know / unsure", "Don't know", q_8_5_1), - q_8_5_2 = ifelse(q_8_7 == "Don't know / unsure", "Don't know", q_8_5_2), - q_8_5_3 = ifelse(q_8_7 == "Don't know / unsure", "Don't know", q_8_5_3), - q_11_1 = ifelse(q_11_1 == "Not enough water to meet any of the above needs", "No", "Yes"), - q_15_1 = ifelse(q_15_1 %in% c("16-21 hours per day", "22+ hours per day"), "16+ hours per day", q_15_1), - q_16_4_b = q_16_4_b/0.0071, - q_16_4_a = ifelse(q_16_4_currency == "Turkish Lira (TRY)", q_16_4_b, q_16_4_a), # SYP to TRY on August 1, 2022 - year = 2022 - ) %>% + mutate(q_17_1 = ifelse(q_17_1 %in% c("Don't know / unsure", "Prefer not to answer"), NA, q_17_1), + q_17_3 = ifelse(q_17_3 %in% c("Don't know/unsure", "Don’t know/unsure"), NA, q_17_3), + q_17_3 = ifelse(q_17_3 == "Prefer to not answer", NA, q_17_3), + q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), + q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", + "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), + q_7_1 = ifelse(q_7_1 == "Internally displaced person (IDP)" & q_k10 == "Camp", "IDPs in camps", q_7_1), + q_7_1 = ifelse(q_7_1 == "Internally displaced person (IDP)" & q_k10 != "Camp", "IDPs out of camps", q_7_1), + q_7_1 = ifelse(q_7_1 == "Host population", "Host (Residents)", q_7_1), + q_7_1 = ifelse(q_7_1 == "Returnee (returned in 2022)", "Returnees (2022)", q_7_1), + q_r3 = ifelse(q_r3 == "Widow / Widower", "Widowed", q_r3), + q_8_7 = ifelse(q_8_7 == "Don't know / unsure", "Don't know", q_8_7), + q_8_5_0 = ifelse(q_8_5_0 == "Don't know / unsure", "Don't know", q_8_5_0), + q_8_5_1 = ifelse(q_8_5_1 == "Don't know / unsure", "Don't know", q_8_5_1), + q_8_5_2 = ifelse(q_8_5_2 == "Don't know / unsure", "Don't know", q_8_5_2), + q_8_5_3 = ifelse(q_8_5_3 == "Don't know / unsure", "Don't know", q_8_5_3), + q_11_1 = ifelse(q_11_1 == "Not enough water to meet any of the above needs", "No", "Yes"), + q_15_1 = ifelse(q_15_1 %in% c("16-21 hours per day", "22+ hours per day"), "16+ hours per day", q_15_1), + q_16_4_b = q_16_4_b/0.0071, + q_16_4_a = ifelse(q_16_4_currency == "Turkish Lira (TRY)", q_16_4_b, q_16_4_a), # SYP to TRY on August 1, 2022 + year = 2022, + year = as.character(year) + ) %>% rename( limit = q_16_3_1, income = q_16_4_a ) %>% - select( - id, q_7_1, q_k7, q_k8, q_k9, q_r1, q_r2, q_r3, q_r12, q_8_7, safety_1, - safety_2, safety_3, safety_4, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_17_1, - q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_2, q_7_2_1, q_7_4, q_7_6, q_7_7, - q_7_9_1, q_7_9_2, q_7_9_3, issues_1, issues_2, issues_3, q_10_1, q_11_1, - q_15_1, q_9_4_1, q_16_2, limit, income, q_16_4, year, q_k11 - ) %>% + select( + id, q_7_1, q_k7, q_k8, q_k9, q_r1, q_r2, q_r3, q_r12, q_8_7, safety_1, + safety_2, safety_3, safety_4, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_17_1, + q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_2, q_7_2_1, q_7_4, q_7_6, q_7_7, + q_7_9_1, q_7_9_2, q_7_9_3, issues_1, issues_2, issues_3, q_10_1, q_11_1, + q_15_1, q_9_4_1, q_16_2, limit, income, q_16_4, year, q_k11 + ) %>% + filter( + q_7_1 != "IDPs in camps" + ) + +# 2023 +msna_2023 <- + raw_2023 %>% + separate( + safety_boys, + into = c("safety_1", "safetyb"), + sep = " " + ) %>% + separate( + safety_girls, + into = c("safety_2", "safetyg"), + sep = " " + ) %>% + separate( + safety_women, + into = c("safety_3", "safetyw"), + sep = " " + ) %>% + separate( + safety_men, + into = c("safety_4", "safetym"), + sep = " " + ) %>% + separate( + unmet_needs, + into = c("q_16_1_1", "q_16_1_2", "q_16_1_3"), + sep = " " + ) %>% + separate( + q_7_9, + into = c("q_7_9_1", "q_7_9_2", "q_7_9_3", "q_7_9_4"), + sep = " " + ) %>% + separate( + q_10_4, + into = c("issues_1", "issues_2", "issues_3", "issues_4", "issues_5"), + sep = " " + ) %>% + separate( + q_16_3, + into = c("limit", "limit_o"), + sep = " " + ) %>% + separate( + barriers_healthcare, + into = c("barr_health", "barriers_0"), + sep = " " + ) %>% + separate( + unex_events, + into = c("event_1", "event_2", "event_3", "event_4"), + sep = " " + ) %>% + separate( + event_hh_affected, + into = c("affect_1", "affect_2", "affect_3", "affect_4"), + sep = " " + ) %>% + mutate( + q_7_1 = ifelse(q_7_1 == "Returnees", "Returnees (2023)", q_7_1), + barr_health = str_replace_all(barr_health, "_", " "), + affect_1 = str_replace_all(affect_1, "_", " "), + affect_2 = str_replace_all(affect_2, "_", " "), + affect_3 = str_replace_all(affect_3, "_", " "), + event_1 = str_replace_all(event_1, "_", " "), + event_2 = str_replace_all(event_2, "_", " "), + event_3 = str_replace_all(event_3, "_", " "), + safety_1 = str_replace_all(safety_1, "_", " "), + safety_2 = str_replace_all(safety_2, "_", " "), + safety_3 = str_replace_all(safety_3, "_", " "), + safety_4 = str_replace_all(safety_4, "_", " "), + q_16_1_1 = str_replace_all(q_16_1_1, "_", " "), + q_16_1_2 = str_replace_all(q_16_1_2, "_", " "), + q_16_1_3 = str_replace_all(q_16_1_3, "_", " "), + q_7_9_1 = str_replace_all(q_7_9_1, "_", " "), + q_7_9_2 = str_replace_all(q_7_9_2, "_", " "), + q_7_9_3 = str_replace_all(q_7_9_3, "_", " "), + issues_1 = str_replace_all(issues_1, "_", " "), + issues_2 = str_replace_all(issues_2, "_", " "), + issues_3 = str_replace_all(issues_3, "_", " "), + limit = str_replace_all(limit, "_", " "), + q_17_3 = ifelse(q_17_3 %in% c("Prefer not to answer", "Don't know"), NA, q_17_3), + q_17_3 = ifelse(q_17_3 == "Neither satisfied nor dissatisfied with all assistance/access to services received", "Don’t know/unsure", q_17_3), + q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), + q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", + "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), + q_11_1 = ifelse(q_11_1 %in% c("Never (0 days)", "Don’t know/unsure", " Rarely (1–2 days)", "Sometimes (3–10 days)"), "No", "Yes"), + q_15_1 = ifelse(q_15_1 == 0, "0 hours per day", + ifelse(q_15_1 %in% 1:2, "1-2 hours per day", + ifelse(q_15_1 >= 3 & q_15_1 <= 8, "3-8 hours per day", + ifelse(q_15_1 >= 9 & q_15_1 <= 15, "9-15 hours per day", + ifelse(q_15_1 >= 16, "16+ hours per day", q_15_1))))), + income = coalesce(q_16_4_a, 0) + coalesce(q_16_4_b, 0) + coalesce(q_16_4_c, 0) + + coalesce(q_16_4_d, 0) + coalesce(q_16_4_e, 0) + coalesce(q_16_4_f, 0) + + coalesce(q_16_4_g, 0) + coalesce(q_16_4_h, 0) + coalesce(q_16_4_i, 0) + + coalesce(q_16_4_j, 0) + coalesce(q_16_4_k, 0) + coalesce(q_16_4_l, 0) + + coalesce(q_16_4_m, 0), + income = ifelse(q_16_4_currency == "Turkish Lira (TRY)", income/0.0020, income), # SYP to TRY on September 20, 2023 + income = ifelse(q_16_4_currency == "US Dollars (USD)", income/0.000076, income), # SYP to USD on September 20, 2023 + aid_kind = str_replace_all(aid_kind, "_", " "), + nutrition_3m = str_replace_all(nutrition_3m, "_", " "), + community = str_split(q_k11, " - ", simplify = TRUE)[, 2], + q_k11 = str_split(q_k11, " - ", simplify = TRUE)[, 1], + q_7_1 = ifelse(q_7_1 == "Residents", "Host (Residents)", q_7_1), + year = 2023, + q_8_5_2 = ifelse(q_8_5_2 == "Don't know / unsure", "Don't know", q_8_5_2), + q_8_5_3 = ifelse(q_8_5_3 == "Don't know / unsure", "Don't know", q_8_5_3), + q_17_3 = ifelse(q_17_3 %in% c("Don't know/unsure", "Don’t know/unsure"), NA, q_17_3), # Revisar este + year = as.character(year) + ) %>% + select( + id, q_7_1, q_k7, q_k8, q_k9, q_r1, q_r2, q_r3, q_r12, q_8_7, safety_1, + safety_2, safety_3, safety_4, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_17_1, + q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_2, q_7_2_1, q_7_4, q_7_6, q_7_7, + aid_kind, q_7_9_1, q_7_9_2, q_7_9_3, issues_1, issues_2, issues_3, q_10_1, + q_11_1, nutrition_3m, q_15_1, barr_health, q_16_2, q_16_4, limit, income, + event_1, event_2, event_3, affect_1, affect_2, affect_3, year, q_k11, community + ) %>% filter( q_7_1 != "IDPs in camps" ) - # 2023 - msna_2023 <- - raw_2023 %>% - separate( - safety_boys, - into = c("safety_1", "safetyb"), - sep = " " - ) %>% - separate( - safety_girls, - into = c("safety_2", "safetyg"), - sep = " " - ) %>% - separate( - safety_women, - into = c("safety_3", "safetyw"), - sep = " " - ) %>% - separate( - safety_men, - into = c("safety_4", "safetym"), - sep = " " - ) %>% - separate( - unmet_needs, - into = c("q_16_1_1", "q_16_1_2", "q_16_1_3"), - sep = " " - ) %>% - separate( - q_7_9, - into = c("q_7_9_1", "q_7_9_2", "q_7_9_3", "q_7_9_4"), - sep = " " - ) %>% - separate( - q_10_4, - into = c("issues_1", "issues_2", "issues_3", "issues_4", "issues_5"), - sep = " " - ) %>% - separate( - q_16_3, - into = c("limit", "limit_o"), - sep = " " - ) %>% - separate( - barriers_healthcare, - into = c("barr_health", "barriers_0"), - sep = " " - ) %>% - separate( - unex_events, - into = c("event_1", "event_2", "event_3", "event_4"), - sep = " " - ) %>% - separate( - event_hh_affected, - into = c("affect_1", "affect_2", "affect_3", "affect_4"), - sep = " " - ) %>% - mutate( - q_7_1 = ifelse(q_7_1 == "Returnees", "Returnees (2023)", q_7_1), - barr_health = str_replace_all(barr_health, "_", " "), - affect_1 = str_replace_all(affect_1, "_", " "), - affect_2 = str_replace_all(affect_2, "_", " "), - affect_3 = str_replace_all(affect_3, "_", " "), - event_1 = str_replace_all(event_1, "_", " "), - event_2 = str_replace_all(event_2, "_", " "), - event_3 = str_replace_all(event_3, "_", " "), - safety_1 = str_replace_all(safety_1, "_", " "), - safety_2 = str_replace_all(safety_2, "_", " "), - safety_3 = str_replace_all(safety_3, "_", " "), - safety_4 = str_replace_all(safety_4, "_", " "), - q_16_1_1 = str_replace_all(q_16_1_1, "_", " "), - q_16_1_2 = str_replace_all(q_16_1_2, "_", " "), - q_16_1_3 = str_replace_all(q_16_1_3, "_", " "), - q_7_9_1 = str_replace_all(q_7_9_1, "_", " "), - q_7_9_2 = str_replace_all(q_7_9_2, "_", " "), - q_7_9_3 = str_replace_all(q_7_9_3, "_", " "), - issues_1 = str_replace_all(issues_1, "_", " "), - issues_2 = str_replace_all(issues_2, "_", " "), - issues_3 = str_replace_all(issues_3, "_", " "), - limit = str_replace_all(limit, "_", " "), - q_17_3 = ifelse(q_17_3 %in% c("Prefer not to answer", "Don't know"), NA, q_17_3), - q_17_3 = ifelse(q_17_3 == "Neither satisfied nor dissatisfied with all assistance/access to services received", "Don’t know/unsure", q_17_3), - q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), - q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", - "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), - q_11_1 = ifelse(q_11_1 %in% c("Never (0 days)", "Don’t know/unsure", " Rarely (1–2 days)", "Sometimes (3–10 days)"), "No", "Yes"), - q_15_1 = ifelse(q_15_1 == 0, "0 hours per day", - ifelse(q_15_1 %in% 1:2, "1-2 hours per day", - ifelse(q_15_1 >= 3 & q_15_1 <= 8, "3-8 hours per day", - ifelse(q_15_1 >= 9 & q_15_1 <= 15, "9-15 hours per day", - ifelse(q_15_1 >= 16, "16+ hours per day", q_15_1))))), - income = coalesce(q_16_4_a, 0) + coalesce(q_16_4_b, 0) + coalesce(q_16_4_c, 0) + - coalesce(q_16_4_d, 0) + coalesce(q_16_4_e, 0) + coalesce(q_16_4_f, 0) + - coalesce(q_16_4_g, 0) + coalesce(q_16_4_h, 0) + coalesce(q_16_4_i, 0) + - coalesce(q_16_4_j, 0) + coalesce(q_16_4_k, 0) + coalesce(q_16_4_l, 0) + - coalesce(q_16_4_m, 0), - income = ifelse(q_16_4_currency == "Turkish Lira (TRY)", income/0.0020, income), # SYP to TRY on September 20, 2023 - income = ifelse(q_16_4_currency == "US Dollars (USD)", income/0.000076, income), # SYP to USD on September 20, 2023 - aid_kind = str_replace_all(aid_kind, "_", " "), - nutrition_3m = str_replace_all(nutrition_3m, "_", " "), - community = str_split(q_k11, " - ", simplify = TRUE)[, 2], - q_k11 = str_split(q_k11, " - ", simplify = TRUE)[, 1], - q_7_1 = ifelse(q_7_1 == "Residents", "Host (Residents)", q_7_1), - year = 2023 - ) %>% - select( - id, q_7_1, q_k7, q_k8, q_k9, q_r1, q_r2, q_r3, q_r12, q_8_7, safety_1, - safety_2, safety_3, safety_4, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_17_1, - q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_2, q_7_2_1, q_7_4, q_7_6, q_7_7, - aid_kind, q_7_9_1, q_7_9_2, q_7_9_3, issues_1, issues_2, issues_3, q_10_1, - q_11_1, nutrition_3m, q_15_1, barr_health, q_16_2, q_16_4, limit, income, - event_1, event_2, event_3, affect_1, affect_2, affect_3, year, q_k11, community - ) %>% - filter( - q_7_1 != "IDPs in camps" - ) - - common_values <- intersect(msna_2022$q_k11, msna_2023$q_k11) - - sample_2022 <- msna_2022 %>% - filter(q_k11 %in% common_values) - - sample_2023 <- msna_2023 %>% - filter(q_k11 %in% common_values) - # Data append ------------------------------------------------------------------ - - msna <- bind_rows(sample_2022, sample_2023) %>% - mutate( - q_8_5_2 = ifelse(q_8_5_2 == "Don't know / unsure", "Don't know", q_8_5_2), - q_8_5_3 = ifelse(q_8_5_3 == "Don't know / unsure", "Don't know", q_8_5_3), - q_17_3 = ifelse(q_17_3 %in% c("Don't know/unsure", "Don’t know/unsure"), NA, q_17_3), # Revisar este - year = as.character(year) - ) + +common_values <- intersect(msna_2022$q_k11, msna_2023$q_k11) + +sample_2022 <- msna_2022 %>% + filter(q_k11 %in% common_values) + +sample_2023 <- msna_2023 %>% + filter(q_k11 %in% common_values) + +msna <- bind_rows(sample_2022, sample_2023) # Data quality ----------------------------------------------------------------- - - # Check missing values for each variable - #missing_values <- raw_2022 %>% - # summarise_all(~sum(is.na(.))) - - # Display missing values - #print(missing_values) - - # To see unique values and frequency - #table(raw_2022$HoH_employ) - \ No newline at end of file + +# Check missing values for each variable +#missing_values <- raw_2022 %>% +# summarise_all(~sum(is.na(.))) + +# Display missing values +#print(missing_values) + +# To see unique values and frequency +#table(raw_2022$HoH_employ) + +# Data coded saving ------------------------------------------------------------ + +# MSNA 2022 +msna_2022 %>% + write_csv( + path = here( + "Data", + "Coded", + "msna_2022.csv") + ) + +# MSNA 2023 +msna_2023 %>% + write_csv( + path = here( + "Data", + "Coded", + "msna_2023.csv") + ) + +# MSNA SAMPLE SEM +msna %>% + write_csv( + path = here( + "Data", + "Coded", + "msna_2023.csv") + ) + +# Earthquake +earthquake %>% + write_csv( + path = here( + "Data", + "Coded", + "earthquake.csv") + ) + +# Shapefiles +syria_shp %>% + write_csv( + path = here( + "Data", + "Coded", + "syria_shp.csv") + ) diff --git a/notebooks/msna/Codes/3_4_hh_welfare.R b/notebooks/msna/Codes/3_4_hh_welfare.R index 61ec9413..e942f639 100644 --- a/notebooks/msna/Codes/3_4_hh_welfare.R +++ b/notebooks/msna/Codes/3_4_hh_welfare.R @@ -36,7 +36,7 @@ for (value in unique_year) { axis.text = element_blank(), axis.title = element_blank(), panel.grid = element_blank()) + - scale_fill_manual(values = pie_colors4) + + scale_fill_manual(values = pie_colors) + facet_wrap(~q_7_1, ncol = 3) ggsave(here("Output", paste0("pie_elec_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) @@ -75,7 +75,7 @@ nutri <- sample_2023 %>% axis.text = element_blank(), axis.title = element_blank(), panel.grid = element_blank()) + - scale_fill_manual(values = pie_colors4) + + scale_fill_manual(values = pie_colors) + facet_wrap(~q_7_1, ncol = 3) ggsave(here("Output", "pie_nut_2023.png"), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) @@ -205,7 +205,7 @@ for (value in unique_year) { axis.text = element_blank(), axis.title = element_blank(), panel.grid = element_blank()) + - scale_fill_manual(values = pie_colors4) + + scale_fill_manual(values = pie_colors) + facet_wrap(~q_7_1, ncol = 3) ggsave(here("Output", paste0("pie_bn_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) diff --git a/notebooks/msna/Codes/maps.do b/notebooks/msna/Codes/maps.do index 7cc55ebc..10a12ffd 100644 --- a/notebooks/msna/Codes/maps.do +++ b/notebooks/msna/Codes/maps.do @@ -58,7 +58,7 @@ label values catIDPs_new cat */ - * Population + * Percentage of hh with access to aid gen catIDPs_new=. replace catIDPs_new=1 if pop==0 replace catIDPs_new=2 if pop>0 & pop<=325 @@ -77,7 +77,7 @@ ******************* Map - * Population + * forvalues i=1/3 { preserve @@ -94,6 +94,8 @@ restore } + + *spshape2dta "${data}\Raw\syr_admbnda_adm3_uncs_unocha_20201217-polygon.shp", replace saving(syria3) * Camp From 764b730b4f92aa87299db54a96a113f649f08ff0 Mon Sep 17 00:00:00 2001 From: ivilaco Date: Wed, 10 Jan 2024 11:31:59 -0500 Subject: [PATCH 5/5] Code updates --- notebooks/msna/0_master.R | 2 +- notebooks/msna/Codes/1_cleaning.R | 538 ++++++------ notebooks/msna/Codes/3_1_conflict.R | 113 ++- notebooks/msna/Codes/3_2_aid.R | 265 ++++-- notebooks/msna/Codes/3_3_displacement.R | 256 ++++-- notebooks/msna/Codes/3_4_hh_welfare.R | 1006 +++++++++++++++++++---- 6 files changed, 1597 insertions(+), 583 deletions(-) diff --git a/notebooks/msna/0_master.R b/notebooks/msna/0_master.R index 6d4bfbaa..8c71d515 100644 --- a/notebooks/msna/0_master.R +++ b/notebooks/msna/0_master.R @@ -25,7 +25,7 @@ library(RColorBrewer) # Colors ----------------------------------------------------------------------- -pie_colors <- c("#66c2e0", "#fae10b", "#fc8d62", "darkseagreen3", "lightpink1", "lightsteelblue1") +pie_colors <- c("#66c2e0", "#fae10b", "#fc8d62", "darkseagreen3", "lightpink1", "lightsteelblue1", "darkblue") bar_colors <- c("#66c2e0", "#fae10b", "#fc8d62") # Codes ------------------------------------------------------------------------ diff --git a/notebooks/msna/Codes/1_cleaning.R b/notebooks/msna/Codes/1_cleaning.R index 8d1662b2..cf353012 100644 --- a/notebooks/msna/Codes/1_cleaning.R +++ b/notebooks/msna/Codes/1_cleaning.R @@ -6,247 +6,327 @@ # Import raw data -------------------------------------------------------------- -raw_2022 <- - read_xlsx( - here( - "Data", - "Raw", - "2022-09-06_SYR_MSNA2022_dataset_HHs.xlsx" - ), - sheet = "Dataset - households" - ) - -raw_2023 <- - read_xlsx( - here( - "Data", - "Raw", - "MSNA2023_dataset.xlsx" - ), - sheet = "Dataset - households" - ) + # Households + raw_2022 <- + read_xlsx( + here( + "Data", + "Raw", + "2022-09-06_SYR_MSNA2022_dataset_HHs.xlsx" + ), + sheet = "Dataset - households" + ) + + raw_2023 <- + read_xlsx( + here( + "Data", + "Raw", + "MSNA2023_dataset.xlsx" + ), + sheet = "Dataset - households" + ) -raw_e <- - read_xlsx( - here( - "Data", - "Raw", - "syria-earthquake-impact-20-march-2023.xlsx" - ), - sheet = "DATASET" - ) + # Individuals + raw_i_2022 <- + read_xlsx( + here( + "Data", + "Raw", + "2022-09-06_SYR_MSNA2022_dataset_individuals.xlsx" + ), + sheet = "Dataset - individuals" + ) + + raw_i_2023 <- + read_xlsx( + here( + "Data", + "Raw", + "MSNA2023_dataset.xlsx" + ), + sheet = "Dataset - individual" + ) -syria_shp <- - st_read( - here( - "Data", - "Raw", - "syr_admbnda_adm3_uncs_unocha_20201217-polygon.shp" + # Earthquake + raw_e <- + read_xlsx( + here( + "Data", + "Raw", + "syria-earthquake-impact-20-march-2023.xlsx" + ), + sheet = "DATASET" + ) + + # Shapefile Syria + syria_shp <- + st_read( + here( + "Data", + "Raw", + "syr_admbnda_adm3_uncs_unocha_20201217-polygon.shp" + ) ) - ) # Data preparation ------------------------------------------------------------- -# Earthquake -earthquake <- raw_e %>% - select(ADM3_EN, ADM3_PCODE, ADM4_EN, ADM4_PCODE, casualties, injuries, - des_houses, damag_houses) %>% - group_by(ADM3_PCODE) %>% - summarise( - total_casualties = sum(casualties, na.rm = TRUE), - total_injuries = sum(injuries, na.rm = TRUE), - total_des_houses = sum(des_houses, na.rm = TRUE), - total_damag_houses = sum(damag_houses, na.rm = TRUE) - ) %>% - mutate( - earthquake = 1 - ) - -# 2022 -msna_2022 <- - raw_2022 %>% - filter(q_k10 != "Neighborhood") %>% - separate( - q_16_8, - into = c("safety_1", "safety_2", "safety_3", "safety_4", "safety_5"), - sep = "; " - ) %>% - separate( - q_10_4, - into = c("issues_1", "issues_2", "issues_3", "issues_4", "issues_5"), - sep = "; " - ) %>% - mutate(q_17_1 = ifelse(q_17_1 %in% c("Don't know / unsure", "Prefer not to answer"), NA, q_17_1), - q_17_3 = ifelse(q_17_3 %in% c("Don't know/unsure", "Don’t know/unsure"), NA, q_17_3), - q_17_3 = ifelse(q_17_3 == "Prefer to not answer", NA, q_17_3), - q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), - q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", - "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), - q_7_1 = ifelse(q_7_1 == "Internally displaced person (IDP)" & q_k10 == "Camp", "IDPs in camps", q_7_1), - q_7_1 = ifelse(q_7_1 == "Internally displaced person (IDP)" & q_k10 != "Camp", "IDPs out of camps", q_7_1), - q_7_1 = ifelse(q_7_1 == "Host population", "Host (Residents)", q_7_1), - q_7_1 = ifelse(q_7_1 == "Returnee (returned in 2022)", "Returnees (2022)", q_7_1), - q_r3 = ifelse(q_r3 == "Widow / Widower", "Widowed", q_r3), - q_8_7 = ifelse(q_8_7 == "Don't know / unsure", "Don't know", q_8_7), - q_8_5_0 = ifelse(q_8_5_0 == "Don't know / unsure", "Don't know", q_8_5_0), - q_8_5_1 = ifelse(q_8_5_1 == "Don't know / unsure", "Don't know", q_8_5_1), - q_8_5_2 = ifelse(q_8_5_2 == "Don't know / unsure", "Don't know", q_8_5_2), - q_8_5_3 = ifelse(q_8_5_3 == "Don't know / unsure", "Don't know", q_8_5_3), - q_11_1 = ifelse(q_11_1 == "Not enough water to meet any of the above needs", "No", "Yes"), - q_15_1 = ifelse(q_15_1 %in% c("16-21 hours per day", "22+ hours per day"), "16+ hours per day", q_15_1), - q_16_4_b = q_16_4_b/0.0071, - q_16_4_a = ifelse(q_16_4_currency == "Turkish Lira (TRY)", q_16_4_b, q_16_4_a), # SYP to TRY on August 1, 2022 - year = 2022, - year = as.character(year) - ) %>% - rename( - limit = q_16_3_1, - income = q_16_4_a - ) %>% - select( - id, q_7_1, q_k7, q_k8, q_k9, q_r1, q_r2, q_r3, q_r12, q_8_7, safety_1, - safety_2, safety_3, safety_4, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_17_1, - q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_2, q_7_2_1, q_7_4, q_7_6, q_7_7, - q_7_9_1, q_7_9_2, q_7_9_3, issues_1, issues_2, issues_3, q_10_1, q_11_1, - q_15_1, q_9_4_1, q_16_2, limit, income, q_16_4, year, q_k11 - ) %>% - filter( - q_7_1 != "IDPs in camps" - ) - -# 2023 -msna_2023 <- - raw_2023 %>% - separate( - safety_boys, - into = c("safety_1", "safetyb"), - sep = " " - ) %>% - separate( - safety_girls, - into = c("safety_2", "safetyg"), - sep = " " - ) %>% - separate( - safety_women, - into = c("safety_3", "safetyw"), - sep = " " - ) %>% - separate( - safety_men, - into = c("safety_4", "safetym"), - sep = " " - ) %>% - separate( - unmet_needs, - into = c("q_16_1_1", "q_16_1_2", "q_16_1_3"), - sep = " " - ) %>% - separate( - q_7_9, - into = c("q_7_9_1", "q_7_9_2", "q_7_9_3", "q_7_9_4"), - sep = " " - ) %>% - separate( - q_10_4, - into = c("issues_1", "issues_2", "issues_3", "issues_4", "issues_5"), - sep = " " - ) %>% - separate( - q_16_3, - into = c("limit", "limit_o"), - sep = " " - ) %>% - separate( - barriers_healthcare, - into = c("barr_health", "barriers_0"), - sep = " " - ) %>% - separate( - unex_events, - into = c("event_1", "event_2", "event_3", "event_4"), - sep = " " - ) %>% - separate( - event_hh_affected, - into = c("affect_1", "affect_2", "affect_3", "affect_4"), - sep = " " - ) %>% - mutate( - q_7_1 = ifelse(q_7_1 == "Returnees", "Returnees (2023)", q_7_1), - barr_health = str_replace_all(barr_health, "_", " "), - affect_1 = str_replace_all(affect_1, "_", " "), - affect_2 = str_replace_all(affect_2, "_", " "), - affect_3 = str_replace_all(affect_3, "_", " "), - event_1 = str_replace_all(event_1, "_", " "), - event_2 = str_replace_all(event_2, "_", " "), - event_3 = str_replace_all(event_3, "_", " "), - safety_1 = str_replace_all(safety_1, "_", " "), - safety_2 = str_replace_all(safety_2, "_", " "), - safety_3 = str_replace_all(safety_3, "_", " "), - safety_4 = str_replace_all(safety_4, "_", " "), - q_16_1_1 = str_replace_all(q_16_1_1, "_", " "), - q_16_1_2 = str_replace_all(q_16_1_2, "_", " "), - q_16_1_3 = str_replace_all(q_16_1_3, "_", " "), - q_7_9_1 = str_replace_all(q_7_9_1, "_", " "), - q_7_9_2 = str_replace_all(q_7_9_2, "_", " "), - q_7_9_3 = str_replace_all(q_7_9_3, "_", " "), - issues_1 = str_replace_all(issues_1, "_", " "), - issues_2 = str_replace_all(issues_2, "_", " "), - issues_3 = str_replace_all(issues_3, "_", " "), - limit = str_replace_all(limit, "_", " "), - q_17_3 = ifelse(q_17_3 %in% c("Prefer not to answer", "Don't know"), NA, q_17_3), - q_17_3 = ifelse(q_17_3 == "Neither satisfied nor dissatisfied with all assistance/access to services received", "Don’t know/unsure", q_17_3), - q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), - q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", - "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), - q_11_1 = ifelse(q_11_1 %in% c("Never (0 days)", "Don’t know/unsure", " Rarely (1–2 days)", "Sometimes (3–10 days)"), "No", "Yes"), - q_15_1 = ifelse(q_15_1 == 0, "0 hours per day", - ifelse(q_15_1 %in% 1:2, "1-2 hours per day", - ifelse(q_15_1 >= 3 & q_15_1 <= 8, "3-8 hours per day", - ifelse(q_15_1 >= 9 & q_15_1 <= 15, "9-15 hours per day", - ifelse(q_15_1 >= 16, "16+ hours per day", q_15_1))))), - income = coalesce(q_16_4_a, 0) + coalesce(q_16_4_b, 0) + coalesce(q_16_4_c, 0) + - coalesce(q_16_4_d, 0) + coalesce(q_16_4_e, 0) + coalesce(q_16_4_f, 0) + - coalesce(q_16_4_g, 0) + coalesce(q_16_4_h, 0) + coalesce(q_16_4_i, 0) + - coalesce(q_16_4_j, 0) + coalesce(q_16_4_k, 0) + coalesce(q_16_4_l, 0) + - coalesce(q_16_4_m, 0), - income = ifelse(q_16_4_currency == "Turkish Lira (TRY)", income/0.0020, income), # SYP to TRY on September 20, 2023 - income = ifelse(q_16_4_currency == "US Dollars (USD)", income/0.000076, income), # SYP to USD on September 20, 2023 - aid_kind = str_replace_all(aid_kind, "_", " "), - nutrition_3m = str_replace_all(nutrition_3m, "_", " "), - community = str_split(q_k11, " - ", simplify = TRUE)[, 2], - q_k11 = str_split(q_k11, " - ", simplify = TRUE)[, 1], - q_7_1 = ifelse(q_7_1 == "Residents", "Host (Residents)", q_7_1), - year = 2023, - q_8_5_2 = ifelse(q_8_5_2 == "Don't know / unsure", "Don't know", q_8_5_2), - q_8_5_3 = ifelse(q_8_5_3 == "Don't know / unsure", "Don't know", q_8_5_3), - q_17_3 = ifelse(q_17_3 %in% c("Don't know/unsure", "Don’t know/unsure"), NA, q_17_3), # Revisar este - year = as.character(year) - ) %>% - select( - id, q_7_1, q_k7, q_k8, q_k9, q_r1, q_r2, q_r3, q_r12, q_8_7, safety_1, - safety_2, safety_3, safety_4, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_17_1, - q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_2, q_7_2_1, q_7_4, q_7_6, q_7_7, - aid_kind, q_7_9_1, q_7_9_2, q_7_9_3, issues_1, issues_2, issues_3, q_10_1, - q_11_1, nutrition_3m, q_15_1, barr_health, q_16_2, q_16_4, limit, income, - event_1, event_2, event_3, affect_1, affect_2, affect_3, year, q_k11, community - ) %>% - filter( - q_7_1 != "IDPs in camps" - ) + # Earthquake + earthquake <- raw_e %>% + select(ADM3_EN, ADM3_PCODE, ADM4_EN, ADM4_PCODE, casualties, injuries, + des_houses, damag_houses) %>% + group_by(ADM3_PCODE) %>% + summarise( + total_casualties = sum(casualties, na.rm = TRUE), + total_injuries = sum(injuries, na.rm = TRUE), + total_des_houses = sum(des_houses, na.rm = TRUE), + total_damag_houses = sum(damag_houses, na.rm = TRUE) + ) %>% + mutate( + earthquake = 1 + ) + + # 2022 - Individuals + msna_i_2022 <- + raw_i_2022 %>% + separate( + edu_3, + into = c("edu3_1", "edu3_2"), + sep = "; " + ) %>% + rename( + id = id_hh, + edu_3 = edu3_1 + ) %>% + select(id_individual, id, edu_1, edu_3, q_7_1, region) %>% + mutate( + year = 2022 + ) + + # 2023 - Individuals + msna_i_2023 <- + raw_i_2023 %>% + select(id_individual, id, edu_1, edu_3, q_7_1, region) %>% + mutate( + year = 2023 + ) + + # 2022 - Households + msna_2022 <- + raw_2022 %>% + filter(q_k10 != "Neighborhood") %>% + separate( + q_16_8, + into = c("safety_1", "safety_2", "safety_3", "safety_4", "safety_5"), + sep = "; " + ) %>% + separate( + q_10_4, + into = c("issues_1", "issues_2", "issues_3", "issues_4", "issues_5"), + sep = "; " + ) %>% + mutate(q_17_1 = ifelse(q_17_1 %in% c("Don't know / unsure", "Prefer not to answer"), NA, q_17_1), + q_17_3 = ifelse(q_17_3 %in% c("Don't know/unsure", "Don’t know/unsure"), NA, q_17_3), + q_17_3 = ifelse(q_17_3 == "Prefer to not answer", NA, q_17_3), + q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), + q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", + "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), + q_7_1 = ifelse(q_7_1 == "Internally displaced person (IDP)" & q_k10 == "Camp", "IDPs in camps", q_7_1), + q_7_1 = ifelse(q_7_1 == "Internally displaced person (IDP)" & q_k10 != "Camp", "IDPs out of camps", q_7_1), + q_7_1 = ifelse(q_7_1 == "Host population", "Host (Residents)", q_7_1), + q_7_1 = ifelse(q_7_1 == "Returnee (returned in 2022)", "Returnees (2022)", q_7_1), + q_r3 = ifelse(q_r3 == "Widow / Widower", "Widowed", q_r3), + q_8_7 = ifelse(q_8_7 == "Don't know / unsure", "Don't know", q_8_7), + q_8_5_0 = ifelse(q_8_5_0 == "Don't know / unsure", "Don't know", q_8_5_0), + q_8_5_1 = ifelse(q_8_5_1 == "Don't know / unsure", "Don't know", q_8_5_1), + q_8_5_2 = ifelse(q_8_5_2 == "Don't know / unsure", "Don't know", q_8_5_2), + q_8_5_3 = ifelse(q_8_5_3 == "Don't know / unsure", "Don't know", q_8_5_3), + q_11_1 = ifelse(q_11_1 == "Not enough water to meet any of the above needs", "No", "Yes"), + q_15_1 = ifelse(q_15_1 %in% c("16-21 hours per day", "22+ hours per day"), "16+ hours per day", q_15_1), + q_16_4_b = q_16_4_b/0.0071, + q_16_4_a = ifelse(q_16_4_currency == "Turkish Lira (TRY)", q_16_4_b, q_16_4_a), # SYP to TRY on August 1, 2022 + year = 2022, + year = as.character(year) + ) %>% + rename( + limit = q_16_3_1, + income = q_16_4_a + ) %>% + select( + id, q_7_1, q_k7, q_k8, q_k9, q_r1, q_r2, q_r3, q_r12, q_8_7, safety_1, + safety_2, safety_3, safety_4, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_17_1, + q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_2, q_7_2_1, q_7_4, q_7_6, q_7_7, + q_7_9_1, q_7_9_2, q_7_9_3, issues_1, issues_2, issues_3, q_10_1, q_11_1, + q_15_1, q_9_4_1, q_16_2, limit, income, q_16_4, year, q_k11, region + ) %>% + filter( + q_7_1 != "IDPs in camps" + ) + + # 2023 - Households + msna_2023 <- + raw_2023 %>% + separate( + safety_boys, + into = c("safety_1", "safetyb"), + sep = " " + ) %>% + separate( + safety_girls, + into = c("safety_2", "safetyg"), + sep = " " + ) %>% + separate( + safety_women, + into = c("safety_3", "safetyw"), + sep = " " + ) %>% + separate( + safety_men, + into = c("safety_4", "safetym"), + sep = " " + ) %>% + separate( + unmet_needs, + into = c("q_16_1_1", "q_16_1_2", "q_16_1_3"), + sep = " " + ) %>% + separate( + aid_kind, + into = c("aid_1", "aid_2", "aid_3", "aid_4"), + sep = " " + ) %>% + separate( + q_7_9, + into = c("q_7_9_1", "q_7_9_2", "q_7_9_3", "q_7_9_4"), + sep = " " + ) %>% + separate( + q_10_4, + into = c("issues_1", "issues_2", "issues_3", "issues_4", "issues_5"), + sep = " " + ) %>% + separate( + q_16_3, + into = c("limit", "limit_o"), + sep = " " + ) %>% + separate( + barriers_healthcare, + into = c("barr_health", "barriers_0"), + sep = " " + ) %>% + separate( + unex_events, + into = c("event_1", "event_2", "event_3", "event_4"), + sep = " " + ) %>% + separate( + event_hh_affected, + into = c("affect_1", "affect_2", "affect_3", "affect_4"), + sep = " " + ) %>% + separate( + q_10_4_e, + into = c("waste_1", "waste_2", "waste_3", "waste_4"), + sep = " " + ) %>% + mutate( + q_7_1 = ifelse(q_7_1 == "Returnees", "Returnees (2023)", q_7_1), + barr_health = str_replace_all(barr_health, "_", " "), + affect_1 = str_replace_all(affect_1, "_", " "), + affect_2 = str_replace_all(affect_2, "_", " "), + affect_3 = str_replace_all(affect_3, "_", " "), + waste_1 = str_replace_all(waste_1, "_", " "), + waste_2 = str_replace_all(waste_2, "_", " "), + waste_3 = str_replace_all(waste_3, "_", " "), + event_1 = str_replace_all(event_1, "_", " "), + event_2 = str_replace_all(event_2, "_", " "), + event_3 = str_replace_all(event_3, "_", " "), + safety_1 = str_replace_all(safety_1, "_", " "), + safety_2 = str_replace_all(safety_2, "_", " "), + safety_3 = str_replace_all(safety_3, "_", " "), + safety_4 = str_replace_all(safety_4, "_", " "), + q_16_1_1 = str_replace_all(q_16_1_1, "_", " "), + q_16_1_2 = str_replace_all(q_16_1_2, "_", " "), + q_16_1_3 = str_replace_all(q_16_1_3, "_", " "), + q_7_9_1 = str_replace_all(q_7_9_1, "_", " "), + q_7_9_2 = str_replace_all(q_7_9_2, "_", " "), + q_7_9_3 = str_replace_all(q_7_9_3, "_", " "), + issues_1 = str_replace_all(issues_1, "_", " "), + issues_2 = str_replace_all(issues_2, "_", " "), + issues_3 = str_replace_all(issues_3, "_", " "), + limit = str_replace_all(limit, "_", " "), + q_17_3 = ifelse(q_17_3 %in% c("Prefer not to answer", "Don't know"), NA, q_17_3), + q_17_3 = ifelse(q_17_3 == "Neither satisfied nor dissatisfied with all assistance/access to services received", "Don’t know/unsure", q_17_3), + q_17_3 = ifelse(q_17_3 == "No, not satisfied with any of the assistance/access to services received", "No", q_17_3), + q_17_3 = ifelse(q_17_3 %in% c("Yes, satisfied with some assistance/access to services received", + "Yes, satisfied with all assistance/access to services received"), "Yes", q_17_3), + q_11_1 = ifelse(q_11_1 %in% c("Never (0 days)", "Don’t know/unsure", " Rarely (1–2 days)", "Sometimes (3–10 days)"), "No", "Yes"), + q_15_1 = ifelse(q_15_1 == 0, "0 hours per day", + ifelse(q_15_1 %in% 1:2, "1-2 hours per day", + ifelse(q_15_1 >= 3 & q_15_1 <= 8, "3-8 hours per day", + ifelse(q_15_1 >= 9 & q_15_1 <= 15, "9-15 hours per day", + ifelse(q_15_1 >= 16, "16+ hours per day", q_15_1))))), + income = coalesce(q_16_4_a, 0) + coalesce(q_16_4_b, 0) + coalesce(q_16_4_c, 0) + + coalesce(q_16_4_d, 0) + coalesce(q_16_4_e, 0) + coalesce(q_16_4_f, 0) + + coalesce(q_16_4_g, 0) + coalesce(q_16_4_h, 0) + coalesce(q_16_4_i, 0) + + coalesce(q_16_4_j, 0) + coalesce(q_16_4_k, 0) + coalesce(q_16_4_l, 0) + + coalesce(q_16_4_m, 0), + income = ifelse(q_16_4_currency == "Turkish Lira (TRY)", income/0.0020, income), # SYP to TRY on September 20, 2023 + income = ifelse(q_16_4_currency == "US Dollars (USD)", income/0.000076, income), # SYP to USD on September 20, 2023 + aid_1 = str_replace_all(aid_1, "_", " "), + aid_2 = str_replace_all(aid_2, "_", " "), + aid_3 = str_replace_all(aid_3, "_", " "), + nutrition_3m = str_replace_all(nutrition_3m, "_", " "), + community = str_split(q_k11, " - ", simplify = TRUE)[, 2], + q_k11 = str_split(q_k11, " - ", simplify = TRUE)[, 1], + q_7_1 = ifelse(q_7_1 == "Residents", "Host (Residents)", q_7_1), + year = 2023, + q_8_5_2 = ifelse(q_8_5_2 == "Don't know / unsure", "Don't know", q_8_5_2), + q_8_5_3 = ifelse(q_8_5_3 == "Don't know / unsure", "Don't know", q_8_5_3), + q_17_3 = ifelse(q_17_3 %in% c("Don't know/unsure", "Don’t know/unsure"), NA, q_17_3), # Revisar este + year = as.character(year) + ) %>% + select( + id, q_7_1, q_k7, q_k8, q_k9, q_r1, q_r2, q_r3, q_r12, q_8_7, safety_1, + safety_2, safety_3, safety_4, q_8_5_0, q_8_5_1, q_8_5_2, q_8_5_3, q_17_1, + q_17_3, q_16_1_1, q_16_1_2, q_16_1_3, q_7_2, q_7_2_1, q_7_4, q_7_6, q_7_7, + aid_1, aid_2, aid_3, q_7_9_1, q_7_9_2, q_7_9_3, issues_1, issues_2, issues_3, q_10_1, + q_11_1, nutrition_3m, q_15_1, barr_health, q_16_2, q_16_4, limit, income, + event_1, event_2, event_3, affect_1, affect_2, affect_3, year, q_k11, community, + q_10_4_g, q_10_4_h, waste_1, waste_2, waste_3, region + ) %>% + filter( + q_7_1 != "IDPs in camps" + ) # Data append ------------------------------------------------------------------ -common_values <- intersect(msna_2022$q_k11, msna_2023$q_k11) + # Select values of communities in common between 2022 and 2023 + common_values <- intersect(msna_2022$q_k11, msna_2023$q_k11) + + # Sample de household databases with the communities in common + sample_2022 <- msna_2022 %>% + filter(q_k11 %in% common_values) + + sample_2023 <- msna_2023 %>% + filter(q_k11 %in% common_values) -sample_2022 <- msna_2022 %>% - filter(q_k11 %in% common_values) + # Select the unique values of households in the sample + hh_2022 <- unique(sample_2022$id) + hh_2023 <- unique(sample_2023$id) -sample_2023 <- msna_2023 %>% - filter(q_k11 %in% common_values) + # Sample de invidiavuals databases with the unique households in the sample + sample_i_2022 <- msna_i_2022 %>% + filter(id %in% hh_2022) + + sample_i_2023 <- msna_i_2023 %>% + filter(id %in% hh_2023) -msna <- bind_rows(sample_2022, sample_2023) + # Append databases + msna <- bind_rows(sample_2022, sample_2023) + msna_i <- bind_rows(sample_i_2022, sample_i_2023) # Data quality ----------------------------------------------------------------- diff --git a/notebooks/msna/Codes/3_1_conflict.R b/notebooks/msna/Codes/3_1_conflict.R index ac7f0d23..af896b49 100644 --- a/notebooks/msna/Codes/3_1_conflict.R +++ b/notebooks/msna/Codes/3_1_conflict.R @@ -41,7 +41,7 @@ ggsave(here("Output", "bar_unsaf_girls.png"), bar_chart, width = 10, height = 6) # Main safety and security concerns in the past 3 months ----------------------- safety <- msna %>% - select(id, starts_with("safety_"), year) %>% + select(id, starts_with("safety_"), year, region) %>% pivot_longer(cols = starts_with("safety"), names_to = "safety_q", values_to = "safety_r") %>% filter(!is.na(safety_r), safety_r != "Don't know/unsure", safety_r != "Dont know", safety_r != "Prefer not to answer") %>% mutate(ones = 1, @@ -79,38 +79,45 @@ safety <- msna %>% "Discrimination on the basis of race, political beliefs, religion, class, age, sex, marital status (widow/divorced), disability, etc."), "Other", safety_r), safety_r = ifelse(safety_r == "Natural disaster earthquake", "Natural disaster (earthquake)", safety_r) ) %>% - group_by(safety_r, year) %>% + group_by(safety_r, year, region) %>% summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% - group_by(year) %>% + group_by(year, region) %>% mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% ungroup() -bar_chart <- ggplot(safety, aes(x = percentage, y = safety_r, fill = year)) + - geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + - geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + - labs(title = "", - x = "Percentage of Households", - y = "Security Concern") + - scale_x_continuous(limits = c(0, max(safety$percentage) + (max(safety$percentage)/10))) + - scale_fill_manual(values = bar_colors) + - theme_minimal() + - theme( - axis.text.y = element_text(size = 8), - axis.text.x = element_text(size = 10), - axis.title = element_text(size = 12, face = "bold"), - plot.title = element_text(size = 16, face = "bold"), - legend.position = "top", - legend.title = element_blank(), - legend.text = element_text(size = 10), - panel.grid.major.y = element_blank(), - panel.grid.minor.y = element_blank(), - panel.grid.major.x = element_line(color = "lightgray", size = 0.5), - panel.grid.minor.x = element_blank() - ) - -ggsave(here("Output", "bar_sec.png"), bar_chart, width = 10, height = 6) +unique_year <- unique(safety$year) +for (value in unique_year) { + + subset_data <- safety %>% + filter(year == value) + + bar_chart <- ggplot(subset_data, aes(x = percentage, y = safety_r, fill = region)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = value, + x = "Percentage of Households", + y = "Security Concern") + + scale_x_continuous(limits = c(0, max(subset_data$percentage) + (max(subset_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("bar_sec_", gsub(" ", "_", value), ".png")), bar_chart, width = 6, height = 7) +} # Levels of stress experienced by a hh member ---------------------------------- @@ -162,3 +169,55 @@ for (value in unique_year) { ggsave(here("Output", paste0("bar_stress_", gsub(" ", "_", value), ".png")), bar_chart, width = 6, height = 6.5) } + +# Levels of stress experienced by a hh member (Region) ------------------------- + +stress <- msna %>% + mutate(stress = ifelse(q_8_5_0 == "Yes" | q_8_5_1 == "Yes" | q_8_5_2 == "Yes" | q_8_5_3 == "Yes", "Yes", "No"), + stress = ifelse((q_8_5_0 == "No" & is.na(stress)) | (q_8_5_1 == "No" & is.na(stress)) | (q_8_5_2 == "No" & is.na(stress)) | (q_8_5_3 == "No" & is.na(stress)), "No", stress), + ones = 1) %>% + filter(!is.na(stress)) %>% + group_by(stress, region, year) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') + +unique_year <- unique(stress$year) + +for (value in unique_year) { + + subset_data <- stress %>% + filter(year == value) %>% + transform(percentage = total / tapply(total, region, sum)[region]*100) %>% + mutate(percentage = round(percentage, 0)) + + bar_chart <- ggplot(subset_data, aes(x = region, y = percentage, fill = stress)) + + geom_bar(stat = "identity") + + geom_text(aes(label = scales::percent(percentage, scale = 1)), + position = position_stack(vjust = 0.5), + size = 3, + color = "black", + show.legend = FALSE) + + labs(title = value, + x = "Population type", + y = "Percentage of households", + fill = "") + + theme_minimal() + + coord_flip() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank(), + legend.position = "bottom", + legend.box = "horizontal" + ) + + scale_fill_manual(values = bar_colors) + + ggsave(here("Output", paste0("bar_stress_r", gsub(" ", "_", value), ".png")), bar_chart, width = 6, height = 6.5) + +} + diff --git a/notebooks/msna/Codes/3_2_aid.R b/notebooks/msna/Codes/3_2_aid.R index 0113b7e8..e7c58aee 100644 --- a/notebooks/msna/Codes/3_2_aid.R +++ b/notebooks/msna/Codes/3_2_aid.R @@ -43,6 +43,91 @@ } } +# Aid kind by region and pop type (2023) --------------------------------------- + + # Pop type + aid_k <- msna %>% + select(id, q_7_1, starts_with("aid_"), year) %>% + pivot_longer(cols = starts_with("aid_"), names_to = "aid_q", values_to = "aid_kind") %>% + mutate(id = id, + ones = 1, + aid_kind = ifelse(aid_kind == "Services e g healthcare education nutrition", "Public services", aid_kind), + aid_kind = ifelse(aid_kind == "Construction rehabilitation of infrastructure water points latrines roads etc", "Construction of infraestructure", aid_kind), + aid_kind = ifelse(aid_kind == "Prefer not to answer", NA, aid_kind) + ) %>% + filter(year == 2023, !is.na(aid_kind)) %>% + group_by(aid_kind, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + group_by(q_7_1) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + bar_chart <- ggplot(aid_k, aes(x = percentage, y = aid_kind, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Aid Kind") + + scale_x_continuous(limits = c(0, max(aid_k$percentage) + (max(aid_k$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", "/bar_aidk_2023.png"), bar_chart, width = 7, height = 6) + + # Region + aid_k <- msna %>% + select(id, region, starts_with("aid_"), year) %>% + pivot_longer(cols = starts_with("aid_"), names_to = "aid_q", values_to = "aid_kind") %>% + mutate(id = id, + ones = 1, + aid_kind = ifelse(aid_kind == "Services e g healthcare education nutrition", "Public services", aid_kind), + aid_kind = ifelse(aid_kind == "Construction rehabilitation of infrastructure water points latrines roads etc", "Construction of infraestructure", aid_kind), + aid_kind = ifelse(aid_kind == "Prefer not to answer", NA, aid_kind) + ) %>% + filter(year == 2023, !is.na(aid_kind)) %>% + group_by(aid_kind, region) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + group_by(region) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + bar_chart <- ggplot(aid_k, aes(x = percentage, y = aid_kind, fill = region)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Aid Kind") + + scale_x_continuous(limits = c(0, max(aid_k$percentage) + (max(aid_k$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", "/bar_aidk_r_2023.png"), bar_chart, width = 7, height = 6) # Aid satisfaction ------------------------------------------------------------- @@ -81,75 +166,119 @@ for (value in unique_year) { ggsave(here("Output", paste0("pie_aid_sat_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) } -# Priority needs --------------------------------------------------------------- - -needs <- msna %>% - select(id, q_7_1, q_16_1_1, year) %>% - rename(need = q_16_1_1) %>% - filter(need != "All needs are met") %>% - mutate(id = id, - ones = 1, - need = ifelse(need %in% c("Dont know", "Don't know/unsure", "Prefer not to answer"), NA, need), - need = ifelse(need %in% c("Food", "Nutrition nutrition services"), "Food/nutrition", need), - need = ifelse(need %in% c("Access to safe water", "Electricity provisio internet", - "Electricity provision", "Sanitation", "Waste disposal"), "WASH and electricity", need), - need = ifelse(need %in% c("Access to community centers and safe spaces for women and girls", - "NFI items", "NFI items (e.g. clothing, blankets, cooking material, sanitation items, fuel and school equipment)", - "Shelter assistance", "Shelter assistance (emergency shelter provision, shelter repairs, rent subsidies)"), "Shelter and NFI items", need), - need = ifelse(need %in% c("Disability-specific needs (medical equipment, medicine, services)", - "Disability specific needs medical equipment medicine services assistive devices to support access to work or education", - "Health services", "Medicine", - "Mental health and psychosocial support services", - "Mental health and psychosocial support services (e.g. structured group activities in a safe space, invididual or group counseling, etc.)"), "Health and medical services", need), - need = ifelse(need %in% c("Education services", "Formal education", - "GBV post services", "Legal advice including civil documentation and Housing Land and Property", - "Legal advice including civil documentation and Housing, Land and Property", - "Livelihood opportunities ability to work", - "Livelihood opportunities/inability to work", - "Non formal education", - "Phone data communication", - "Phone/data/communication", - "Reintegration services", "Risk awareness and clearance (Mine Action)", - "Risk awareness and clearance Mine Action", - "Technical and vocational training", - "Technical and vocational trainings"), "Other", need) - ) %>% - group_by(need, q_7_1, year) %>% - summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% - filter(!is.na(need)) %>% - group_by(q_7_1, year) %>% - mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% - ungroup() +# Priority needs by pop type and region ---------------------------------------- -unique_year <- unique(needs$year) + needs <- msna %>% + select(id, q_7_1, q_16_1_1, year, region) %>% + rename(need = q_16_1_1) %>% + filter(need != "All needs are met") %>% + mutate(id = id, + ones = 1, + need = ifelse(need %in% c("Dont know", "Don't know/unsure", "Prefer not to answer"), NA, need), + need = ifelse(need %in% c("Food", "Nutrition nutrition services"), "Food/nutrition", need), + need = ifelse(need %in% c("Access to safe water", "Sanitation", "Waste disposal"), "WASH access", need), + need = ifelse(need %in% c("Electricity provisio internet", "Electricity provision"), "Electricity provision", need), + need = ifelse(need %in% c("Education services", "Formal education", "Non formal education"), + "Education access", need), + need = ifelse(need %in% c("NFI items", "NFI items (e.g. clothing, blankets, cooking material, sanitation items, fuel and school equipment)"), + "NFI items", need), + need = ifelse(need %in% c("Shelter assistance", "Shelter assistance (emergency shelter provision, shelter repairs, rent subsidies)"), "Shelter assistance", need), + need = ifelse(need %in% c("Livelihood opportunities ability to work", + "Livelihood opportunities/inability to work", + "Technical and vocational training", + "Technical and vocational trainings"), "Work related", need), + need = ifelse(need %in% c("Disability-specific needs (medical equipment, medicine, services)", + "Disability specific needs medical equipment medicine services assistive devices to support access to work or education", + "Health services", "Medicine", + "Mental health and psychosocial support services", + "Mental health and psychosocial support services (e.g. structured group activities in a safe space, invididual or group counseling, etc.)"), + "Health and medical services", need), + need = ifelse(need %in% c("Risk awareness and clearance (Mine Action)", + "Risk awareness and clearance Mine Action", + "Access to community centers and safe spaces for women and girls", + "GBV post services", "Phone data communication", + "Phone/data/communication"), "Other", need), + need = ifelse(need %in% c("Legal advice including civil documentation and Housing Land and Property", + "Legal advice including civil documentation and Housing, Land and Property", + "Reintegration services"), "Legal and reintegration assistance", need) + ) -for (value in unique_year) { - plot_data <- filter(needs, year == value) + # Pop type + needs_pt <- needs %>% + group_by(need, q_7_1, year) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(need)) %>% + group_by(q_7_1, year) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() - bar_chart <- ggplot(plot_data, aes(x = percentage, y = need, fill = q_7_1)) + - geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + - geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + - labs(title = value, - x = "Percentage of Households", - y = "Need") + - scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + - scale_fill_manual(values = bar_colors) + - theme_minimal() + - theme( - axis.text.y = element_text(size = 8), - axis.text.x = element_text(size = 10), - axis.title = element_text(size = 12, face = "bold"), - plot.title = element_text(size = 16, face = "bold"), - legend.position = "top", - legend.title = element_blank(), - legend.text = element_text(size = 10), - panel.grid.major.y = element_blank(), - panel.grid.minor.y = element_blank(), - panel.grid.major.x = element_line(color = "lightgray", size = 0.5), - panel.grid.minor.x = element_blank() - ) + unique_year <- unique(needs$year) - ggsave(here("Output", paste0("/bar_need", gsub("/", "_", value), ".png")), bar_chart, width = 7.5, height = 6) -} - -# GoS-issued documentation ----------------------------------------------------- + for (value in unique_year) { + plot_data <- filter(needs_pt, year == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = need, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = value, + x = "Percentage of Households", + y = "Need") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("/bar_need", gsub("/", "_", value), ".png")), bar_chart, width = 7, height = 8) + } + + # Region + needs_r <- needs %>% + group_by(need, region, year) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(need)) %>% + group_by(region, year) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + unique_year <- unique(needs$year) + + for (value in unique_year) { + plot_data <- filter(needs_r, year == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = need, fill = region)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = value, + x = "Percentage of Households", + y = "Need") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("/bar_need_r_", gsub("/", "_", value), ".png")), bar_chart, width = 7, height = 8) + } diff --git a/notebooks/msna/Codes/3_3_displacement.R b/notebooks/msna/Codes/3_3_displacement.R index 96307cc1..ca5a35b3 100644 --- a/notebooks/msna/Codes/3_3_displacement.R +++ b/notebooks/msna/Codes/3_3_displacement.R @@ -127,10 +127,10 @@ ggsave(here("Output", "time_idp_arr.png"), plot = time_chart, width = 10, height ggsave(here("Output", "hist_time_disp.png"), plot = hist_chart, width = 9, height = 6, units = "in", dpi = 300) -# Main reasons for displacement for IPS households ----------------------------- +# Main reasons for displacement for IPS households by region ----------------------------- push <- msna %>% - select(id, year, q_7_9_1) %>% + select(id, year, q_7_9_1, region) %>% rename( push = q_7_9_1 ) %>% @@ -138,98 +138,151 @@ push <- msna %>% ones = 1, push = ifelse(push == "Worse security situation in last place lived", "Security reasons", push), push = ifelse(push %in% c("Pursuit of better economic situation lower prices livelihood opportunities", - "Worse economic situation last place lived", - "Worse livelihood opportunities in last placce lived", - "Unacceptable living conditions (lack of water, power, sewage, privacy/overcrowding, heating, safety, etc.) in last place lived"), "Economic and livelihood reasons", push), + "Worse economic situation last place lived"), "Economic opportunities", push), + push = ifelse(push %in% c("Worse livelihood opportunities in last placce lived", + "Unacceptable living conditions (lack of water, power, sewage, privacy/overcrowding, heating, safety, etc.) in last place lived"), "Other", push), push = ifelse(push %in% c("Family reasons to reunite with family or to be close to family", - "Insufficient/no availability of humanitarian assistance in last place lived", - "Insufficient/no availability of public services in last place lived (health, education, markets, WASH, etc.)", - "Pursuit of better public services", - "Separated from my family in last place lived", - "Pursuit of humanitarian assistance"), "Other", push) + "Separated from my family in last place lived"), "Family reasons", push), + push = ifelse(push %in% c("Insufficient/no availability of humanitarian assistance in last place lived", + "Pursuit of humanitarian assistance"), "Humanitarian assistance", push), + push = ifelse(push %in% c("Insufficient/no availability of public services in last place lived (health, education, markets, WASH, etc.)", + "Pursuit of better public services"), "Public services availability", push) ) %>% - group_by(push, year) %>% + group_by(push, year, region) %>% summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% filter(!is.na(push)) %>% - group_by(year) %>% + group_by(year, region) %>% mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% ungroup() -bar_chart <- ggplot(push, aes(x = percentage, y = push, fill = year)) + - geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + - geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + - labs(title = "", - x = "Percentage of Households", - y = "Push Factor") + - scale_x_continuous(limits = c(0, max(push$percentage) + (max(push$percentage)/10))) + - scale_fill_manual(values = bar_colors) + - theme_minimal() + - theme( - axis.text.y = element_text(size = 8), - axis.text.x = element_text(size = 10), - axis.title = element_text(size = 12, face = "bold"), - plot.title = element_text(size = 16, face = "bold"), - legend.position = "top", - legend.title = element_blank(), - legend.text = element_text(size = 10), - panel.grid.major.y = element_blank(), - panel.grid.minor.y = element_blank(), - panel.grid.major.x = element_line(color = "lightgray", size = 0.5), - panel.grid.minor.x = element_blank() - ) +unique_year <- unique(push$year) -ggsave(here("Output", "bar_push.png"), bar_chart, width = 9, height = 6) +for (value in unique_year) { + plot_data <- filter(push, year == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = push, fill = region)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = value, + x = "Percentage of Households", + y = "Push Factor") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("bar_push_", gsub("/", "_", value), ".png")), bar_chart, width = 6, height = 6) + } # Type of shelter / housing the hh currently reside (by population type) ------- -type_hh <- msna %>% - select(id, q_7_1, q_10_1, year) %>% - mutate(ones = 1, - q_10_1 = ifelse(q_10_1 %in% c("Other (specify)", - "Substandard building (factory, farm, shop)", - "Prefabricated unit", - "Collective shelter (religious building, school, warehouse)", - "Makeshift shelter", - "Concrete block shelter", - "House/ apartment (unfinished)"), "Other", q_10_1)) - -unique_year <- unique(type_hh$year) + type_hh <- msna %>% + select(id, q_7_1, q_10_1, region, year) %>% + mutate(id = id, + ones = 1, + q_10_1 = ifelse(q_10_1 %in% c("Substandard building (factory, farm, shop)", + "Concrete block shelter", + "Makeshift shelter"), "Other", q_10_1), + q_10_1 = ifelse(q_10_1 == "Collective shelter (religious building, school, warehouse)", "Collective shelter", q_10_1) + ) -for (value in unique_year) { - subset_data <- type_hh %>% - filter(year == value) %>% - group_by(q_7_1, q_10_1) %>% - summarise(n = n()) %>% - mutate(percentage = round(n / sum(n) * 100, 1)) %>% - mutate(csum = rev(cumsum(rev(percentage))), - pos = percentage/2 + lead(csum, 1), - pos = if_else(is.na(pos), percentage/2, pos)) + # Pop type + type_hh_pt <- type_hh %>% + group_by(q_10_1, q_7_1, year) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(q_10_1)) %>% + group_by(q_7_1, year) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() - pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_10_1))) + - geom_bar(stat = "identity", width = 1, color = "white") + - coord_polar(theta = "y") + - geom_label_repel(data = subset_data, - aes(y = pos, label = paste0(percentage, "%")), - size = 3, nudge_x = 0.7, show.legend = FALSE) + - labs(fill = "") + - theme_minimal() + - theme(legend.position = "right", - plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), - plot.caption = element_text(hjust = 0.5, size = 10), - axis.text = element_blank(), - axis.title = element_blank(), - panel.grid = element_blank()) + - scale_fill_manual(values = pie_colors) + - facet_wrap(~q_7_1, ncol = 3) + unique_year <- unique(type_hh_pt$year) - ggsave(here("Output", paste0("pie_st_", gsub(" ", "_", value), ".png")), pie_chart, width = 9, height = 6) -} + for (value in unique_year) { + plot_data <- filter(type_hh_pt, year == value) + + pie_chart <- ggplot(plot_data, aes(x = percentage, y = q_10_1, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = value, + x = "Percentage of Households", + y = "Shelter / Housing Type") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("bar_st_", gsub("/", "_", value), ".png")), pie_chart, width = 7, height = 6) + } + + # Region + type_hh_r <- type_hh %>% + group_by(q_10_1, region, year) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(q_10_1)) %>% + group_by(region, year) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + unique_year <- unique(type_hh_r$year) + + for (value in unique_year) { + plot_data <- filter(type_hh_r, year == value) + + pie_chart <- ggplot(plot_data, aes(x = percentage, y = q_10_1, fill = region)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = value, + x = "Percentage of Households", + y = "Shelter / Housing Type") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("bar_st_r_", gsub("/", "_", value), ".png")), pie_chart, width = 7, height = 6) + } # Adequacy issues in the hh shelter -------------------------------------------- - + issues <- msna %>% - select(id, starts_with("issues_"), year, q_7_1) %>% + select(id, starts_with("issues_"), year, region, q_7_1) %>% pivot_longer(cols = starts_with("issues"), names_to = "issues_q", values_to = "issues_r") %>% filter(!is.na(issues_r)) %>% mutate(ones = 1, @@ -251,7 +304,10 @@ issues <- msna %>% "Poor facilities for persons with specific needs (PwSN) i.e. unable to access due to physical/ health condition"), "Infraestructure issues", issues_r), issues_r = ifelse(issues_r %in% c("Other (please specify)", "Other"), NA, issues_r) - ) %>% + ) + + # Pop type + issues_pt <- issues %>% group_by(issues_r, year, q_7_1) %>% summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% filter(!is.na(issues_r)) %>% @@ -259,10 +315,10 @@ issues <- msna %>% mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% ungroup() -unique_year <- unique(needs$year) +unique_year <- unique(issues_pt$year) for (value in unique_year) { - plot_data <- filter(issues, year == value) + plot_data <- filter(issues_pt, year == value) bar_chart <- ggplot(plot_data, aes(x = percentage, y = issues_r, fill = q_7_1)) + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + @@ -288,4 +344,44 @@ for (value in unique_year) { ) ggsave(here("Output", paste0("bar_issue_", gsub(" ", "_", value), ".png")), bar_chart, width = 7.5, height = 6) -} \ No newline at end of file +} + + # Region + issues_r <- issues %>% + group_by(issues_r, year, region) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(issues_r)) %>% + group_by(region, year) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + unique_year <- unique(issues_r$year) + + for (value in unique_year) { + plot_data <- filter(issues_r, year == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = issues_r, fill = region)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = value, + x = "Percentage of Households", + y = "Adequacy Issue") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("bar_issue_r_", gsub(" ", "_", value), ".png")), bar_chart, width = 7.5, height = 6) + } \ No newline at end of file diff --git a/notebooks/msna/Codes/3_4_hh_welfare.R b/notebooks/msna/Codes/3_4_hh_welfare.R index e942f639..209536ab 100644 --- a/notebooks/msna/Codes/3_4_hh_welfare.R +++ b/notebooks/msna/Codes/3_4_hh_welfare.R @@ -10,19 +10,349 @@ electr <- msna %>% filter(!is.na(q_15_1)) %>% mutate(q_15_1 = factor(q_15_1, levels = c("0 hours per day", "1-2 hours per day", "3-8 hours per day", "9-15 hours per day", "16+ hours per day"))) -unique_year <- unique(electr$year) + # Pop type + unique_year <- unique(electr$year) + + for (value in unique_year) { + subset_data <- electr %>% + filter(year == value) %>% + group_by(q_7_1, q_15_1) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_15_1))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_elec_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) + } + + # Region + subset_data <- electr %>% + mutate(region = ifelse(year == 2022 & region == "NES", "NES - 2022", region), + region = ifelse(year == 2022 & region == "NWS", "NWS - 2022", region), + region = ifelse(year == 2023 & region == "NES", "NES - 2023", region), + region = ifelse(year == 2023 & region == "NWS", "NWS - 2023", region)) %>% + group_by(region, q_15_1) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_15_1))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~region, ncol = 2) + + ggsave(here("Output", paste0("pie_elec_r.png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) -for (value in unique_year) { - subset_data <- electr %>% - filter(year == value) %>% - group_by(q_7_1, q_15_1) %>% +# Challenges with wastewater disposal (2023) ----------------------------------- + +waste <- sample_2023 %>% + select(id, q_7_1, starts_with("waste_"), region) %>% + pivot_longer(cols = starts_with("waste_"), names_to = "waste_q", values_to = "q_10_4_e") %>% + filter(q_10_4_e != "Prefer not to answer", q_10_4_e != "Dont know") %>% + mutate(id = id, + ones = 1, + q_10_4_e = ifelse(q_10_4_e %in% c("The toilet bathing site is not safe no lock bolt ", + "The toilet bathing site is not safe no light", + "It is not safe for children", + "It is not safe bothered while in the toilet bathing site", + "It is not safe bothered on the way to the toilet bathing site", + "The toilet bathing site is not safe no lock bolt"), + "It's not safe", q_10_4_e), + q_10_4_e = ifelse(q_10_4_e %in% c("Lack of privacy no separation in toliets between men and women", + "Lack of privacy no door"), "Lack of privacy", q_10_4_e), + q_10_4_e = ifelse(q_10_4_e %in% c("Toilets located in hidden not visible area", + "No toilet is avaiblable", + "Lack of ability to get to the toilet without assistance", + "Difficulties of elderly people and PWD to access toilets without assistance"), "No access or availability", q_10_4_e), + q_10_4_e = ifelse(q_10_4_e %in% c("The toilt has no handwashing station", + "Septic tank not emptied due to unavailability of desludging service", + "Pipes blocked inside the house", + "Not enough facilities too crowded damaged", + "Connection to sewage blocked", + "Sewage overflowing in the neighbourhood", + "no possible to dispose of diapers mentrsual materials etc"), "Lack of functioning infraestructure", q_10_4_e) + ) + + # Pop type + waste_pt <- waste %>% + group_by(q_10_4_e, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(q_10_4_e)) %>% + group_by(q_7_1) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + bar_chart <- ggplot(waste_pt, aes(x = percentage, y = q_10_4_e, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Challenges") + + scale_x_continuous(limits = c(0, max(waste_pt$percentage) + (max(waste_pt$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", "/bar_cha_waste.png"), bar_chart, width = 7, height = 6) + + # Region + waste_r <- waste %>% + group_by(q_10_4_e, region) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(q_10_4_e)) %>% + group_by(region) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + bar_chart <- ggplot(waste_r, aes(x = percentage, y = q_10_4_e, fill = region)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Challenges") + + scale_x_continuous(limits = c(0, max(waste_r$percentage) + (max(waste_r$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", "/bar_cha_waste_r_.png"), bar_chart, width = 7, height = 6) + +# Type of toilet facility (2023) ----------------------------------------------- + + toilet <- sample_2023 %>% + select(id, q_7_1, q_10_4_g, region) %>% + mutate(id = id, + ones = 1, + q_10_4_g = ifelse(q_10_4_g %in% c("Plastic Bag", + "Bucket", + "Composting toilet", + "Hanging toilet/hanging latrine", + "Flush/pour flush to don't know where"), "Other", q_10_4_g) + ) + + # Pop type + toilet_pt <- toilet %>% + group_by(q_10_4_g, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(q_10_4_g)) %>% + group_by(q_7_1) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + bar_chart <- ggplot(toilet_pt, aes(x = percentage, y = q_10_4_g, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Toilet Type") + + scale_x_continuous(limits = c(0, max(toilet_pt$percentage) + (max(toilet_pt$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", "/bar_toilet.png"), bar_chart, width = 7, height = 6) + + # Region + toilet_r <- toilet %>% + group_by(q_10_4_g, region) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(q_10_4_g)) %>% + group_by(region) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + bar_chart <- ggplot(toilet_r, aes(x = percentage, y = q_10_4_g, fill = region)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Toilet Type") + + scale_x_continuous(limits = c(0, max(toilet_r$percentage) + (max(toilet_r$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", "/bar_toilet_r.png"), bar_chart, width = 7, height = 6) + + +# Type of garbage disposal (2023) ---------------------------------------------- + + garbage <- sample_2023 %>% + select(id, q_7_1, q_10_4_h, region) %>% + filter(q_10_4_h != "Prefer not to answer", q_10_4_h != "Don’t know/unsure") %>% + mutate(ones = 1, + q_10_4_h = ifelse(q_10_4_h == "Garbage disposed of by household to a dumping location", "Dumping location", q_10_4_h), + q_10_4_h = ifelse(q_10_4_h == "Public garbage collection free (or Nominal Fees)", "Public collection free / Nominal Fees)", q_10_4_h)) + + # Pop type + garbage_pt <- garbage %>% + group_by(q_10_4_h, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(q_10_4_h)) %>% + group_by(q_7_1) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + bar_chart <- ggplot(garbage_pt, aes(x = percentage, y = q_10_4_h, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Disposal Type") + + scale_x_continuous(limits = c(0, max(garbage_pt$percentage) + (max(garbage_pt$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", "/bar_disposal.png"), bar_chart, width = 7, height = 6) + + # Region + garbage_r <- garbage %>% + group_by(q_10_4_h, region) %>% + summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% + filter(!is.na(q_10_4_h)) %>% + group_by(region) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + bar_chart <- ggplot(garbage_r, aes(x = percentage, y = q_10_4_h, fill = region)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = "", + x = "Percentage of Households", + y = "Disposal Type") + + scale_x_continuous(limits = c(0, max(garbage_r$percentage) + (max(garbage_r$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", "/bar_disposal_r.png"), bar_chart, width = 7, height = 6) + +# % of HHs reported access to nutrition services in past 3m (2023) ------------- + +nutri <- sample_2023 %>% + mutate( + nutrition_3m = ifelse(nutrition_3m == "Dont know", NA, nutrition_3m), + nutrition_3m = ifelse(nutrition_3m == "No not needed", "No needed", nutrition_3m), + nutrition_3m = ifelse(nutrition_3m != "No needed" & nutrition_3m != "Yes" & + !is.na(nutrition_3m), "No", nutrition_3m), + ) %>% + filter(!is.na(nutrition_3m)) + + # Pop type + subset_data <- nutri %>% + group_by(q_7_1, nutrition_3m) %>% summarise(n = n()) %>% mutate(percentage = round(n / sum(n) * 100, 1)) %>% mutate(csum = rev(cumsum(rev(percentage))), pos = percentage/2 + lead(csum, 1), pos = if_else(is.na(pos), percentage/2, pos)) - pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_15_1))) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(nutrition_3m))) + geom_bar(stat = "identity", width = 1, color = "white") + coord_polar(theta = "y") + geom_label_repel(data = subset_data, @@ -39,22 +369,11 @@ for (value in unique_year) { scale_fill_manual(values = pie_colors) + facet_wrap(~q_7_1, ncol = 3) - ggsave(here("Output", paste0("pie_elec_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) -} - - -# % of HHs reported access to nutrition services in past 3m (2023) ------------- - -nutri <- sample_2023 %>% - mutate( - nutrition_3m = ifelse(nutrition_3m == "Dont know", NA, - ifelse(nutrition_3m == "Yes", "Yes", "No") - ) - ) %>% - filter(!is.na(nutrition_3m)) + ggsave(here("Output", "pie_nut_2023.png"), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) + # Region subset_data <- nutri %>% - group_by(q_7_1, nutrition_3m) %>% + group_by(region, nutrition_3m) %>% summarise(n = n()) %>% mutate(percentage = round(n / sum(n) * 100, 1)) %>% mutate(csum = rev(cumsum(rev(percentage))), @@ -76,10 +395,10 @@ nutri <- sample_2023 %>% axis.title = element_blank(), panel.grid = element_blank()) + scale_fill_manual(values = pie_colors) + - facet_wrap(~q_7_1, ncol = 3) + facet_wrap(~region, ncol = 2) + + ggsave(here("Output", "pie_nut_r_2023.png"), plot = pie_chart, width = 8, height = 6, units = "in", dpi = 300) - ggsave(here("Output", "pie_nut_2023.png"), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) - # % of households reporting having had sufficient water for drinking ----------- wat <- msna %>% @@ -88,17 +407,340 @@ wat <- msna %>% unique_year <- unique(wat$year) + # Pop type + for (value in unique_year) { + subset_data <- wat %>% + filter(year == value) %>% + group_by(q_7_1, q_11_1) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_11_1))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_wat_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) + } + + # Region + wat_r <- wat %>% + mutate(region = ifelse(year == 2022 & region == "NES", "NES - 2022", region), + region = ifelse(year == 2022 & region == "NWS", "NWS - 2022", region), + region = ifelse(year == 2023 & region == "NES", "NES - 2023", region), + region = ifelse(year == 2023 & region == "NWS", "NWS - 2023", region)) + + subset_data <- wat_r %>% + group_by(region, q_11_1) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_11_1))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~region, ncol = 2) + + ggsave(here("Output", "pie_wat_r.png"), plot = pie_chart, width = 8, height = 6, units = "in", dpi = 300) + +# % of HHs by ability to meet the basic needs ---------------------------------- + + bn <- msna %>% + filter(!is.na(q_16_2)) + + unique_year <- unique(bn$year) + + # Pop type + for (value in unique_year) { + subset_data <- bn %>% + filter(year == value) %>% + group_by(q_7_1, q_16_2) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_16_2))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_bn_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) + } + + # Region + subset_data <- bn %>% + mutate(region = ifelse(year == 2022 & region == "NES", "NES - 2022", region), + region = ifelse(year == 2022 & region == "NWS", "NWS - 2022", region), + region = ifelse(year == 2023 & region == "NES", "NES - 2023", region), + region = ifelse(year == 2023 & region == "NWS", "NWS - 2023", region)) %>% + group_by(region, q_16_2) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_16_2))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~region, ncol = 2) + + ggsave(here("Output", "pie_bn_r.png"), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) + +# Main reason limiting household’s ability to meet their basic needs ----------- + +limits <- msna %>% + select(id, year, limit, q_7_1, region) %>% + mutate(id = id, + ones = 1, + limit = ifelse(limit %in% c("Other (please specify)", + "Lack of access to services (health, education, electricity, etc.)", + "Lack of availability of services (health, education, electricity, etc.)", + "Restrictions on movement for non COVID-19 reasons (such as general insecurity, checkpoints, regulations by authorities, presence of explosive ordnance, or others)", + "Unavailability of items (medicines, bread, water, fuel, etc.)", + "Disability of one or more members in the HH", + "Issues related to lack of civil documentation", + "HH no longer receiving assistance", + "Loss of remittances", + "Restrictions on movement", + "Unavailability of items medicines bread water fuel etc", + "Direct losses and or displacement due to the earthquakes"), "Other", limit), + limit = ifelse(limit %in% c("Death absence of primary breadwinner", + "Disability illness of one or more members in the HH leading to bigger expenses", + "Expensive services health education electricity etc", + "Loss of remittances general", + "Eviction housing unable to pay rent", + "Loss of remittances value of money received has decreased no modality to receive"), "Insufficient/lack of income", limit), + limit = ifelse(limit == "Unemployment loss of job", "Unemployment/loss of job", limit) + ) %>% + filter(!is.na(limit), limit != "Prefer not to answer", limit != "No other Reasons") + + # Pop type + limits_pt <- limits %>% + group_by(limit, year, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + group_by(q_7_1, year) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + unique_year <- unique(limits$year) + + for (value in unique_year) { + plot_data <- filter(limits_pt, year == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = limit, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = value, + x = "Percentage of Households", + y = "Limitation") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("/bar_lim", gsub("/", "_", value), ".png")), bar_chart, width = 7.5, height = 6) + } + + # Region + limits_r <- limits %>% + group_by(limit, year, region) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + group_by(region, year) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + unique_year <- unique(limits$year) + + for (value in unique_year) { + plot_data <- filter(limits_r, year == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = limit, fill = region)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = value, + x = "Percentage of Households", + y = "Limitation") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("/bar_lim_r_", gsub("/", "_", value), ".png")), bar_chart, width = 7.5, height = 6) + } + +# Household income over the last 3 months -------------------------------------- + +income <- msna %>% + select(income, year, q_16_4, q_7_1) %>% + filter(q_16_4 == "Yes") + +unique_year <- unique(income$year) + for (value in unique_year) { - subset_data <- wat %>% - filter(year == value) %>% - group_by(q_7_1, q_11_1) %>% + + subset_data <- income %>% + filter(year == value) %>% + mutate( + income = ifelse(income > quantile(income, 0.95, na.rm = TRUE), NA, income) + ) + + hist_chart <- ggplot(subset_data, aes(x = factor(q_7_1), y = income)) + + geom_boxplot(fill = "lightblue", color = "blue") + + labs(title = "Outliers treated at 95%", + x = "Population type", + y = "Syrian Pounds (SYP)") + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("box_income", gsub(" ", "_", value), ".png")), plot = hist_chart, width = 7, height = 6, units = "in", dpi = 300) +} + +# % of individuals in age to attend school that attended school ---------------- + +edu1 <- msna_i %>% + filter(!is.na(edu_1)) + +unique_year <- unique(edu1$year) + + # Pop type + for (value in unique_year) { + subset_data <- edu1 %>% + filter(year == value) %>% + group_by(q_7_1, edu_1) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(edu_1))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) + + ggsave(here("Output", paste0("pie_edu1_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) + } + + # Region + subset_data <- edu1 %>% + mutate(region = ifelse(year == 2022 & region == "NES", "NES - 2022", region), + region = ifelse(year == 2022 & region == "NWS", "NWS - 2022", region), + region = ifelse(year == 2023 & region == "NES", "NES - 2023", region), + region = ifelse(year == 2023 & region == "NWS", "NWS - 2023", region)) %>% + group_by(region, edu_1) %>% summarise(n = n()) %>% mutate(percentage = round(n / sum(n) * 100, 1)) %>% mutate(csum = rev(cumsum(rev(percentage))), pos = percentage/2 + lead(csum, 1), pos = if_else(is.na(pos), percentage/2, pos)) - pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_11_1))) + + pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(edu_1))) + geom_bar(stat = "identity", width = 1, color = "white") + coord_polar(theta = "y") + geom_label_repel(data = subset_data, @@ -113,15 +755,125 @@ for (value in unique_year) { axis.title = element_blank(), panel.grid = element_blank()) + scale_fill_manual(values = pie_colors) + - facet_wrap(~q_7_1, ncol = 3) + facet_wrap(~region, ncol = 2) + + ggsave(here("Output", "pie_edu1_r.png"), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) + +# Main reason not to access formal education ----------------------------------- + +edu2 <- msna_i %>% + mutate(id = id, + ones = 1, + edu_3 = ifelse(edu_3 %in% c("Other (specify)", + "Joined military or armed group", + "School is not gender segregated", + "Child/ren too young"), "Other", edu_3), + edu_3 = ifelse(edu_3 %in% c("Can't afford for children to go/Child/ren working to support HH", + "Child/ren working to support the household", + "Household inability to afford child education"), + "Can't afford, child/ren working to support HH", edu_3), + edu_3 = ifelse(edu_3 == "Child/ren don't want to go to school", "Child/ren don’t want to go to school", edu_3), + edu_3 = ifelse(edu_3 == "Scared of going or being in school (attacks, violence, danger, harassment, or bullying)", "Scared of going or being in school", edu_3), + edu_3 = ifelse(edu_3 == "There is no school for child's age-group", "There is no school for child’s age-group", edu_3), + edu_3 = ifelse(edu_3 %in% c("Dropped out after marriage and/or pregnancy", + "Early marriage/early pregnancies (before 18 years of age)"), + "Marriage and/or pregnancy", edu_3), + edu_3 = ifelse(edu_3 %in% c("Poor water, sanitation and hygiene conditions in schools (lack of latrines, access to (clean) water, etc.)", + "The physical condition of the school is not safe/not good enough", + "The physical condition of the school is not safe/not good enough (including WASH facilities)", + "School not able to accommodate child/ren's disabilities", + "School not able to accommodate child/ren’s disabilities"), + "Poor physical and wash facilities", edu_3) + ) %>% + filter(!is.na(edu_3), + edu_3 != "Don’t know/unsure", + edu_3 != "Prefer not to answer" , + edu_3 != "No other reasons") + + # Pop type + edu2_pt <- edu2 %>% + group_by(edu_3, year, q_7_1) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + group_by(q_7_1, year) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + +unique_year <- unique(edu2_pt$year) + +for (value in unique_year) { + plot_data <- filter(edu2_pt, year == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = edu_3, fill = q_7_1)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = value, + x = "Percentage of individuals", + y = "Main Reason") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) - ggsave(here("Output", paste0("pie_wat_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) + ggsave(here("Output", paste0("/bar_edu3", gsub("/", "_", value), ".png")), bar_chart, width = 7, height = 8) } + # Region + edu2_r <- edu2 %>% + group_by(edu_3, year, region) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + group_by(region, year) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() + + unique_year <- unique(edu2_r$year) + + for (value in unique_year) { + plot_data <- filter(edu2_r, year == value) + + bar_chart <- ggplot(plot_data, aes(x = percentage, y = edu_3, fill = region)) + + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + + labs(title = value, + x = "Percentage of individuals", + y = "Main Reason") + + scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_fill_manual(values = bar_colors) + + theme_minimal() + + theme( + axis.text.y = element_text(size = 8), + axis.text.x = element_text(size = 10), + axis.title = element_text(size = 12, face = "bold"), + plot.title = element_text(size = 16, face = "bold"), + legend.position = "top", + legend.title = element_blank(), + legend.text = element_text(size = 10), + panel.grid.major.y = element_blank(), + panel.grid.minor.y = element_blank(), + panel.grid.major.x = element_line(color = "lightgray", size = 0.5), + panel.grid.minor.x = element_blank() + ) + + ggsave(here("Output", paste0("/bar_edu3_r_", gsub("/", "_", value), ".png")), bar_chart, width = 7, height = 8) + } + # Main reason limiting household’s ability to access healthcare (2023) --------- barr <- sample_2023 %>% - select(id, year, barr_health, q_7_1) %>% + select(id, year, barr_health, q_7_1, region) %>% mutate(id = id, ones = 1, barr_health = ifelse(barr_health %in% c("Turned away at the health facility", @@ -139,23 +891,27 @@ barr <- sample_2023 %>% "No functional health facility nearby"), "Other", barr_health), barr_health = ifelse(barr_health %in% c("Could not afford cost of consultation", "Could not afford cost of treatment", - "Could not afford transportation to health facility"), "Could not afford related costs", barr_health) + "Could not afford transportation to health facility"), "Could not afford related costs", barr_health), + barr_health = ifelse(barr_health == "Specific medicine treatment or service needed unavailable", "Specific treatment or service unavailable", barr_health) ) %>% - filter(!is.na(barr_health), barr_health != "Dont know", barr_health != "Prefer not to answer") %>% + filter(!is.na(barr_health), barr_health != "Dont know", barr_health != "Prefer not to answer") + + # Pop type + barr_pt <- barr %>% group_by(barr_health, year, q_7_1) %>% summarise(total = sum(ones, na.rm = TRUE), .groups = 'drop') %>% group_by(q_7_1, year) %>% mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% ungroup() - - bar_chart <- ggplot(barr, aes(x = percentage, y = barr_health, fill = q_7_1)) + + + bar_chart <- ggplot(barr_pt, aes(x = percentage, y = barr_health, fill = q_7_1)) + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + labs(title = , x = "Percentage of Households", y = "Limitation") + - scale_x_continuous(limits = c(0, max(barr$percentage) + (max(barr$percentage)/10))) + + scale_x_continuous(limits = c(0, max(barr_pt$percentage) + (max(barr_pt$percentage)/10))) + scale_fill_manual(values = bar_colors) + theme_minimal() + theme( @@ -172,91 +928,24 @@ barr <- sample_2023 %>% panel.grid.minor.x = element_blank() ) - ggsave(here("Output", "/bar_barr_2023.png"), bar_chart, width = 9, height = 6) + ggsave(here("Output", "/bar_barr_2023.png"), bar_chart, width = 7, height = 6) -# % of HHs by ability to meet the basic needs ---------------------------------- - -bn <- msna %>% - filter(!is.na(q_16_2)) - -unique_year <- unique(bn$year) - -for (value in unique_year) { - subset_data <- bn %>% - filter(year == value) %>% - group_by(q_7_1, q_16_2) %>% - summarise(n = n()) %>% - mutate(percentage = round(n / sum(n) * 100, 1)) %>% - mutate(csum = rev(cumsum(rev(percentage))), - pos = percentage/2 + lead(csum, 1), - pos = if_else(is.na(pos), percentage/2, pos)) - - pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(q_16_2))) + - geom_bar(stat = "identity", width = 1, color = "white") + - coord_polar(theta = "y") + - geom_label_repel(data = subset_data, - aes(y = pos, label = paste0(percentage, "%")), - size = 3, nudge_x = 0.7, show.legend = FALSE) + - labs(fill = "") + - theme_minimal() + - theme(legend.position = "right", - plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), - plot.caption = element_text(hjust = 0.5, size = 10), - axis.text = element_blank(), - axis.title = element_blank(), - panel.grid = element_blank()) + - scale_fill_manual(values = pie_colors) + - facet_wrap(~q_7_1, ncol = 3) - - ggsave(here("Output", paste0("pie_bn_", gsub(" ", "_", value), ".png")), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) -} - -# Main reason limiting household’s ability to meet their basic needs ----------- - -limits <- msna %>% - select(id, year, limit, q_7_1) %>% - mutate(id = id, - ones = 1, - limit = ifelse(limit %in% c("Other (please specify)", - "Lack of access to services (health, education, electricity, etc.)", - "Lack of availability of services (health, education, electricity, etc.)", - "Restrictions on movement for non COVID-19 reasons (such as general insecurity, checkpoints, regulations by authorities, presence of explosive ordnance, or others)", - "Unavailability of items (medicines, bread, water, fuel, etc.)", - "Disability of one or more members in the HH", - "Issues related to lack of civil documentation", - "HH no longer receiving assistance", - "Loss of remittances", - "Restrictions on movement", - "Unavailability of items medicines bread water fuel etc", - "Direct losses and or displacement due to the earthquakes"), "Other", limit), - limit = ifelse(limit %in% c("Death absence of primary breadwinner", - "Disability illness of one or more members in the HH leading to bigger expenses", - "Expensive services health education electricity etc", - "Loss of remittances general", - "Eviction housing unable to pay rent", - "Loss of remittances value of money received has decreased no modality to receive"), "Insufficient/lack of income", limit), - limit = ifelse(limit == "Unemployment loss of job", "Unemployment/loss of job", limit) - ) %>% - filter(!is.na(limit), limit != "Prefer not to answer", limit != "No other Reasons") %>% - group_by(limit, year, q_7_1) %>% - summarise(total = sum(ones, na.rm = TRUE), - .groups = 'drop') %>% - group_by(q_7_1, year) %>% - mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% - ungroup() - -unique_year <- unique(limits$year) - -for (value in unique_year) { - plot_data <- filter(limits, year == value) + # Region + barr_r <- barr %>% + group_by(barr_health, year, region) %>% + summarise(total = sum(ones, na.rm = TRUE), + .groups = 'drop') %>% + group_by(region, year) %>% + mutate(percentage = round(total / sum(total) * 100, digits = 1)) %>% + ungroup() - bar_chart <- ggplot(plot_data, aes(x = percentage, y = limit, fill = q_7_1)) + + bar_chart <- ggplot(barr_r, aes(x = percentage, y = barr_health, fill = region)) + geom_bar(stat = "identity", position = "dodge", width = 0.7, color = "white") + geom_text(aes(label = percentage), position = position_dodge(width = 0.7), hjust = - 0.5, vjust = 0, size = 2) + - labs(title = value, + labs(title = , x = "Percentage of Households", y = "Limitation") + - scale_x_continuous(limits = c(0, max(plot_data$percentage) + (max(plot_data$percentage)/10))) + + scale_x_continuous(limits = c(0, max(barr_r$percentage) + (max(barr_r$percentage)/10))) + scale_fill_manual(values = bar_colors) + theme_minimal() + theme( @@ -273,8 +962,7 @@ for (value in unique_year) { panel.grid.minor.x = element_blank() ) - ggsave(here("Output", paste0("/bar_lim", gsub("/", "_", value), ".png")), bar_chart, width = 7.5, height = 6) -} + ggsave(here("Output", "/bar_barr_r_2023.png"), bar_chart, width = 7, height = 6) # Access to healthcare (Only 2022) --------------------------------------------- @@ -285,68 +973,30 @@ health_2022 <- sample_2022 %>% ) %>% select(health, q_7_1) - subset_data <- health_2022 %>% - group_by(q_7_1, health) %>% - summarise(n = n()) %>% - mutate(percentage = round(n / sum(n) * 100, 1)) %>% - mutate(csum = rev(cumsum(rev(percentage))), - pos = percentage/2 + lead(csum, 1), - pos = if_else(is.na(pos), percentage/2, pos)) - - pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(health))) + - geom_bar(stat = "identity", width = 1, color = "white") + - coord_polar(theta = "y") + - geom_label_repel(data = subset_data, - aes(y = pos, label = paste0(percentage, "%")), - size = 3, nudge_x = 0.7, show.legend = FALSE) + - labs(fill = "") + - theme_minimal() + - theme(legend.position = "right", - plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), - plot.caption = element_text(hjust = 0.5, size = 10), - axis.text = element_blank(), - axis.title = element_blank(), - panel.grid = element_blank()) + - scale_fill_manual(values = pie_colors) + - facet_wrap(~q_7_1, ncol = 3) - - ggsave(here("Output", "pie_health_2022.png"), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) +subset_data <- health_2022 %>% + group_by(q_7_1, health) %>% + summarise(n = n()) %>% + mutate(percentage = round(n / sum(n) * 100, 1)) %>% + mutate(csum = rev(cumsum(rev(percentage))), + pos = percentage/2 + lead(csum, 1), + pos = if_else(is.na(pos), percentage/2, pos)) -# Household income over the last 3 months -------------------------------------- +pie_chart <- ggplot(subset_data, aes(x = "", y = percentage, fill = fct_inorder(health))) + + geom_bar(stat = "identity", width = 1, color = "white") + + coord_polar(theta = "y") + + geom_label_repel(data = subset_data, + aes(y = pos, label = paste0(percentage, "%")), + size = 3, nudge_x = 0.7, show.legend = FALSE) + + labs(fill = "") + + theme_minimal() + + theme(legend.position = "right", + plot.title = element_text(hjust = 0.5, size = 16, face = "bold"), + plot.caption = element_text(hjust = 0.5, size = 10), + axis.text = element_blank(), + axis.title = element_blank(), + panel.grid = element_blank()) + + scale_fill_manual(values = pie_colors) + + facet_wrap(~q_7_1, ncol = 3) -income <- msna %>% - select(income, year, q_16_4, q_7_1) %>% - filter(q_16_4 == "Yes") - -unique_year <- unique(income$year) +ggsave(here("Output", "pie_health_2022.png"), plot = pie_chart, width = 9, height = 6, units = "in", dpi = 300) -for (value in unique_year) { - - subset_data <- income %>% - filter(year == value) %>% - mutate( - income = ifelse(income > quantile(income, 0.95, na.rm = TRUE), NA, income) - ) - - hist_chart <- ggplot(subset_data, aes(x = factor(q_7_1), y = income)) + - geom_boxplot(fill = "lightblue", color = "blue") + - labs(title = "Outliers treated at 95%", - x = "Population type", - y = "Syrian Pounds (SYP)") + - theme_minimal() + - theme( - axis.text.y = element_text(size = 8), - axis.text.x = element_text(size = 10), - axis.title = element_text(size = 12, face = "bold"), - plot.title = element_text(size = 16, face = "bold"), - legend.position = "top", - legend.title = element_blank(), - legend.text = element_text(size = 10), - panel.grid.major.y = element_blank(), - panel.grid.minor.y = element_blank(), - panel.grid.major.x = element_line(color = "lightgray", size = 0.5), - panel.grid.minor.x = element_blank() - ) - - ggsave(here("Output", paste0("box_income", gsub(" ", "_", value), ".png")), plot = hist_chart, width = 7, height = 6, units = "in", dpi = 300) -} \ No newline at end of file