使用传单和地图将值分配给错误的国家

时间:2019-01-13 12:36:23

标签: r shiny leaflet maps

我正在尝试使用Leaflet绘制欧洲国家/地区,但分配给这些国家/地区的值不正确。目标是创建欧洲的Choropleth地图,其中每个国家都为其分配了特定的值。我使用了原始数据集的样本,在“当前输出”图像中可以看到,瑞典获得了德国的价值。如何为正确的GEO(国家/地区)分配正确的值

require(shiny)
require(leaflet)
require(htmltools)
require(ggplot2)
require(highcharter)
require(maps)
require(dplyr)

rm(list = ls())

df <- data.frame(GEO = c("Belgium", "Germany" , 
"France","Italy","Sweden","Slovakia" ),
             PRODUCT = c("Total petroleum products"),
             TIME = c(1990),
             Value = c(18345, 126544, 88659,90069,14670,4974), 
stringsAsFactors = FALSE)

ui <- fluidPage(
  titlePanel("Energy consumption in Europe"),
  tabsetPanel(
    tabPanel("Map overview", sidebarLayout(
      sidebarPanel(selectInput("Type", "Select Type", choices = 
unique(df$PRODUCT), selected = ""), 
               selectInput("Year", "Select Year", choices = 
unique(df$TIME), selected = "")),
      mainPanel(leafletOutput("firstMap", height = 800)
      )))
  )
)

server <- function(input, output) {

  output$firstMap <- renderLeaflet({

    df_tmp1<-reactive({
      subset(df, df$PRODUCT==input$Type & df$TIME==input$Year)
    })

    df_tmp <-df_tmp1()

    bounds <- map("world", unique(df_tmp$GEO), fill = TRUE, plot = FALSE)
    bounds$Value <- df_tmp$Value
    pal <- colorNumeric("Blues", df$Value)

    leaflet(bounds)%>%
      addTiles()%>%
      addPolygons(stroke = TRUE,
                  smoothFactor = 0.5,
                  fillOpacity=0.8,
                  fillColor = ~pal(df_tmp$Value),
                  color = "black",
                  opacity = 0.7,
                  weight = 1,
                  popup = paste(bounds$names, "<br>", "Value: ", 
df_tmp$Value, "KTOE"
              )
      )%>%
      addLegend("topright", pal = pal, values = df$Value,
                title = "Consumption in KTOE",
                labels = c(min(df$Value), max(df$Value)),
                opacity = 0.6
      )
  })

}


shinyApp(ui, server)

The Current output

我在这里想念什么?

1 个答案:

答案 0 :(得分:0)

这是由于国家/地区的排序所致,您似乎认为这是理所当然的。

bounds <- map("world", unique(df_tmp$GEO), fill = TRUE, plot = FALSE)

将返回您要求的多边形,但不一定以相同的顺序。此外,如果一个国家/地区包含多个多边形(例如,法国也有“ France:Corsica”),这也会使您的数据复杂化。因此只需设置

bounds$Value <- df_tmp$Value

确实会给出相当随机的结果。您必须确保将正确的值与正确的多边形匹配。因此,首先您必须提取国家名称,而不必在边界中添加其他内容:

bounds$country <- vapply(strsplit(bounds$name, ":"), function(x) x[1], FUN.VALUE="a")

现在,您可以为每个条目提供正确的值:

bounds$Value <- df_tmp$Value[match(bounds$country, df_tmp$GEO)]