我试图用r包括一个将数据更新为Cloropeth的按钮。我使用的方法是更新,其主意是我想放置一个按钮,以便将在绳索中显示的数据从GDP更改为人均GDP。我一直在寻找使用更新菜单的范例,但是当我按下地图上消失的任何按钮时,它都无法正常工作。
我在这里附上我一直在使用的代码。我正在学习R,因此对我的代码的任何建议都值得欢迎。
#install.packages(c("devtools","dplyr"))
library(devtools)
#install_github("mingjerli/rWEO")
library(rWEO)
library(plotly)
library(plotlyGeoAssets)
round_df <- function(x, digits) {
# round all numeric variables
# x: data frame
# digits: number of digits to round
numeric_columns <- sapply(x, class) == 'numeric'
x[numeric_columns] <- round(x[numeric_columns], digits)
x
}
df <- read.table('WEOApr2018all.xls', header=TRUE, sep='\t',fill=TRUE, quote="")
can<-df[df$ISO=="BOL"|df$ISO=="COL"|df$ISO=="ECU"|df$ISO=="BOL"|df$ISO=="PER",1:which(colnames(df)=="X2016" )]
can1<-can[can$Subject.Descriptor=="Employment" | can$Subject.Descriptor=="Population" | can$Subject.Descriptor=="Gross domestic product, current prices"| can$Subject.Descriptor=="Gross domestic product per capita, current prices" ,c(2,4,5,7,10:ncol(can))]
can1<-as.data.frame(t(can1[can1$Units=="U.S. dollars" | can1$Units=="Persons" | can1$Units=="Persons" ,c(1:ncol(can1))]))
colnames(can1)<-rep(c("GDP","GDPpc","Employment","Population"),4)
can1<-rbind(can1[5:41,1:4],can1[5:41,5:8],can1[5:41,9:12],can1[5:41,13:16])
can1$Year<-(rep(1980:2016,4))
can1$CODE<-rep(c("BOL","COL","ECU","PER"),c(37,37,37,37))
can1$Country<-rep(c("Bolivia","Colombia","Ecuador","Peru"),c(37,37,37,37))
can1$GDP<-as.numeric(levels(can1$GDP))[can1$GDP]
can1$GDPpc<-as.numeric(gsub(",","",can1$GDPpc,fixed=TRUE))
can1$Population<-as.numeric(levels(can1$Population))[can1$Population]
can1<-round_df(can1,2)
can1$hover <- with(can1, paste(Country,"2016", '<br>', "GDP billions of USD", GDP,'<br>',"GDP per capita USD", GDPpc, "<br>",
"Population millions", Population))
##################
# updatemenus component
updatemenus <- list(
list(
active = -1,
type= 'buttons',
buttons = list(
list(
label = "GDP",
method = "update",
args = list(list(visible = c(TRUE, FALSE)),list(z=~GDP), list(colors='Greens'))),
list(
label = "GDPpc",
method = "update",
args = list(list(visible = c(FALSE, TRUE)),list(z=~GDPpc),list(colors='Blues'))))
))
# light grey boundaries
l <- list(color = toRGB("grey"), width = 0.5)
# specify map projection/options
g <- list( scope = "south america",
showframe = FALSE,
showcoastlines = FALSE,
projection = list(type = 'Mercator')
)
p <- plot_geo(can1) %>%
add_trace(
z =~GDPpc, color = ~GDPpc, colors = 'Blues',
text = ~hover, locations = ~CODE, marker = list(line = l)
) %>%
add_trace(
z =~GDP, color = ~GDP, colors = 'Greens',
text = ~hover, locations = ~CODE, marker = list(line = l)
) %>%
colorbar(title = 'GDP Billions US$', tickprefix = '$') %>%
layout(
title = '2016 Andean Community GDP<br>Source:<a href="https://www.imf.org/external/ns/cs.aspx?id=28">World Economic Outlook</a>',
geo = g,updatemenus=updatemenus)