cjerzak's picture
Update app.R
d2be2d3 verified
raw
history blame
3.27 kB
options(error = NULL)
library(shiny)
library(shinydashboard)
library(dplyr)
library(readr)
library(sf)
library(cartogram)
library(ggplot2)
library(rnaturalearth)
library(rnaturalearthdata)
library(countrycode)
# =============================
# UI
# =============================
ui <- dashboardPage(
dashboardHeader(title = "Country Representation Rankings"),
dashboardSidebar(
sidebarMenu(
menuItem("Cartogram", tabName = "cartogramTab", icon = icon("globe"))
),
# User input: which representation index to display
selectInput(
inputId = "indexChoice",
label = "Select Representation Index:",
choices = c("Overall", "RepresentationGap", "Ethnicity",
"Gender", "Religion", "Language"),
selected = "Overall"
)
),
dashboardBody(
tabItems(
tabItem(
tabName = "cartogramTab",
fluidRow(
box(
width = 12,
plotOutput("cartogramPlot", height = "600px")
)
)
)
)
)
)
# =============================
# SERVER
# =============================
server <- function(input, output, session) {
# ---- Read CSV data and create ISO3 codes ----
rankings_data <- reactive({
read_csv("CountryRepresentationRankings.csv") %>%
# Use countrycode to convert the country names to ISO3 codes
mutate(iso_a3 = countrycode(Country, origin = "country.name", destination = "iso3c"))
})
# ---- Read/prepare world map shapefile ----
world_sf <- reactive({
ne_countries(scale = "medium", returnclass = "sf") %>%
select(name, iso_a3, pop_est, geometry) %>% # includes iso_a3 for merging
st_transform(crs = "ESRI:54009") # projected coordinate system
})
# ---- Create cartogram ----
cartogram_sf <- reactive({
# Merge your CSV data (for coloring) with Natural Earth polygons via ISO3
merged_sf <- world_sf() %>%
left_join(rankings_data(), by = "iso_a3")
merged_sf <- merged_sf[!is.na(merged_sf$Overall),]
# You can choose which variable to use for the cartogram distortion.
# If you want to size by pop_est, use weight = "pop_est"
#cartogram_cont(
#merged_sf,
#weight = "pop_est",
#prepare = TRUE)
#return( cartogram_dorling( merged_sf, weight = "pop_est" ))
return( merged_sf )
})
# ---- Plot output ----
output$cartogramPlot <- renderPlot({
req(input$indexChoice)
index_col <- input$indexChoice
plot_data <- cartogram_sf()
ggplot(plot_data) +
geom_sf(aes_string(fill = index_col), color = "grey20", size = 0.1) +
scale_fill_viridis_c(option = "D", na.value = "white") +
theme_minimal(base_size = 14) +
labs(
fill = paste(index_col, "Index"),
title = "Country Representation Rankings",
subtitle = "Map Colored by Selected Representation Index",
caption = "Source: Global Leadership Project (GLP) & Natural Earth"
) +
theme(
plot.title = element_text(face = "bold"),
axis.text = element_blank(),
axis.ticks = element_blank()
)
})
}
# =============================
# Launch the Shiny App
# =============================
shinyApp(ui = ui, server = server)