library("plotly") # using 4.7.1 (current CRAN version)
# fetches data:
download.file("https://github.com/andreskarjus/artofthefigure/blob/master/evs_example.RData?raw=true", "evs_example.RData", mode = "wb")
load("evs_example.RData")
# the country names from the EVS survey data have been recoded to ISO 3166-1-alpha-3 which is what plot_geo uses to reference countries; this was done using the countrycodes package which matches between various names and code formats.
# buttons:
# adapted from https://plot.ly/r/custom-buttons/
updatemenus <- list(
list(
active = 0,
type= 'buttons',
showactive = F,
buttons = list(
list(
label = names(eur2)[1],
method = "update",
args = list(list(visible = c(T, T, F,F, F)))),
list(
label = names(eur2)[2],
method = "update",
args = list(list(visible = c(T,F, T,F,F))))
,list(
label = names(eur2)[3],
method = "update",
args = list(list(visible = c(T,F, F,T,F))))
,list(
label = names(eur2)[4],
method = "update",
args = list(list(visible = c(T,F, F,F,T))))
)))
# colors:
cols=c("red", "lightgray", "green")
plot_geo() %>%
add_trace(z = ~value, data = eur2[[1]], locations = c("x"), color = ~value, colors = cols,visible=T,showscale=T) %>% # dummy trace for constant legend
add_trace(z = ~value, data = eur2[[1]], locations = ~country, color = ~value, colors = cols,visible=T,showscale=FALSE) %>%
add_trace(z = ~value, data = eur2[[2]], locations = ~country, color = ~value, colors =cols,visible=F,showscale=FALSE) %>%
add_trace(z = ~value, data = eur2[[3]], locations = ~country, color = ~value, colors = cols,visible=F,showscale=F) %>%
add_trace(z = ~value, data = eur2[[4]], locations = ~country, color = ~value, colors = cols,visible=F,showscale=F) %>%
layout(geo = list(scope="europe", projection=list(scale=1.35)),
title="EVS Question E069-07: Confidence in the parliament",
margin=list(l=0,r=0,b=0,t=30), updatemenus=updatemenus) %>%
colorbar(title = "", thickness=10, which=1, yanchor="bottom", x=1)
Feel free to make use of this but kindly cite https://github.com/andreskarjus/artofthefigure (and of course the plotly authors) if you do :)