传单弹出图与地图不对应

Leaflet popup graphs don't correspond to map

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

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

Covid 数据: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

我认为您在 Clean_Deaths$state 中有州的缩写(例如,“NY”),在 states$NAME 中有完整的州名(例如,“New York”)。

在您的 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"))

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