【问题标题】:Leaflet popup graphs don't correspond to map传单弹出图与地图不对应
【发布时间】:2020-10-21 00:48:44
【问题描述】:

我正在尝试使用传单包将 choropleth 地图制作为 html 小部件。我不想为此处理闪亮的事情。我有每个州的 covid 死亡时间序列数据。我希望能够单击状态并弹出相应的时间序列图。我已经很接近了,但我的问题是当您单击某个状态时弹出的图表与该状态不正确对应。例如,如果您点击俄亥俄州,就会弹出一张西弗吉尼亚州地图。

形状文件数据:https://www.census.gov/cgi-bin/geo/shapefiles/index.php?year=2019&layergroup=States+%28and+equivalent%29

新冠病毒数据:https://data.cdc.gov/Case-Surveillance/United-States-COVID-19-Cases-and-Deaths-by-State-o/9mfq-cb36

library(tidyverse)
library(lubridate)
library(readr)
library(leaflet)
library(tigris)
library(rgdal)
library(leafpop)

states <- readOGR(dsn = "tl_2019_us_state", layer = "tl_2019_us_state")

covid_deaths<- read_csv("covid_deaths_usafacts.csv")
Clean_Deaths<- covid_deaths%>%
  select(submission_date, state, tot_cases,new_case,tot_death,new_death)%>%
  filter(new_death>=0)%>%
  mutate(submission_date=as.Date(Clean_Deaths$submission_date, "%m/%d/%Y"))

my_list <- list()  
loop<-for (i in unique(Clean_Deaths$state)) {
state<-Clean_Deaths%>% filter(state==i)
  plot<-ggplot(state, aes(x = submission_date, y = new_death)) + 
    geom_line()+scale_x_date(date_breaks = "1 month",date_labels = "%b")+labs(title = i)
  my_list[[i]] <- plot
}

m1 <- leaflet() %>%
  addTiles() %>%
  setView(lng = -120.5, lat = 44, zoom = 6)%>%
  addPolygons(data = states, 
              fillColor = "red",
              fillOpacity = 0.6,       
              color = "darkgrey",      
              weight = 1.5, 
              popup = popupGraph(my_list)
              )
  m1

【问题讨论】:

    标签: r choropleth htmlwidgets r-leaflet


    【解决方案1】:

    我认为您在 Clean_Deaths$state 中有州的缩写(例如,“NY”),而您在 states$NAME 中有州的全名(例如,“纽约”)。

    在您的filter 中,您可以从一种转换为另一种。您的for 循环可以通过states$NAME,这将匹配您在地图中使用的data

    for (i in states$NAME) {
      state<-Clean_Deaths%>% filter(state==state.abb[match(i, state.name)])
      plot<-ggplot(state, aes(x = submission_date, y = new_death)) + 
        geom_line()+scale_x_date(date_breaks = "1 month",date_labels = "%b")+labs(title = i)
      my_list[[i]] <- plot
    }
    

    以下是使用 lapply 并简化后的类似内容:

    my_list <- lapply(states$NAME, function(i) {
      Clean_Deaths %>%
        filter(state == state.abb[match(i, state.name)]) %>%
        ggplot(aes(x = submission_date, y = new_death)) +
          geom_line() +
          scale_x_date(date_breaks = "1 month",date_labels = "%b") +
          labs(title = i)
    })
    

    顺便说一句,在此之前您的mutate 不需要管道中引用的数据框:

    mutate(submission_date=as.Date(submission_date, "%m/%d/%Y"))
    

    如果这能解决您的问题,请告诉我。

    【讨论】:

    • 是的!非常感谢!!
    猜你喜欢
    • 2020-07-07
    • 2020-10-19
    • 2018-09-05
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多