# US Adult Obesity 2016
library(rgdal)
library(sp)
library(leaflet)
library(geojsonio)
library(RColorBrewer)
library(dplyr)
# Set working directory
setwd("C:/~/App US Adult Obesity")
# Read csv
obesity <- read.csv("US Adult Obesity.csv", header = TRUE)
# Read geojson file
states <- geojson_read("gz_2010_us_040_00_500k.json", what = "sp")
View(states)
# Match data
obesity.map.2016 <- merge(states, obesity, by.x = "NAME", by.y = "State")
class(obesity.map.2016)
View(obesity.map.2016)
# Create a palette
obesity$Year.2016 <- as.numeric(as.character(obesity$Year.2016))
pal <- colorBin("Reds", c(22, 38), na.color = "#808080")
#, alpha = FALSE, reverse = FALSE)
# Create a popup
state_popup <- paste0("<strong>State: </strong>",
obesity$state,
"<br><strong>% of adult obesity in 2016: </strong>",
obesity$Year.2016)
# Create a map
leaflet(obesity.map.2016) %>%
addProviderTiles(providers$Stamen.TonerLite) %>%
setView(lng = -98.583, lat = 39.833, zoom = 4) %>%
addPolygons(color = "#444444", weight = 1,
# opacity = 0.5,
fillOpacity = 0.7,
fillColor = ~pal(obesity$Year.2016),
popup = state_popup) %>%
addLegend("bottomright", pal = pal, values = ~obesity$Year.2016,
opacity = 1,
title = "US Adult Obesity in 2016 by State")
因此,我在加利福尼亚州收到了明尼苏达州的数据。视图显示它不匹配,我有50个状态+ DC。 我不敢相信我忘记了怎么做。 有关我愚蠢错误的任何提示吗?
答案 0 :(得分:1)
亲自解决。看起来我搞砸了价值观,使用的不是来自df,而是来自csv。
# US Adult Obesity 2016
library(rgdal)
library(sp)
library(leaflet)
library(geojsonio)
# Set working directory
setwd("C:/~US Adult Obesity")
# Read csv, which was created specifically
obesity <- read.csv("US Adult Obesity.csv", header = TRUE)
# Read geojson file
states <- geojson_read("gz_2010_us_040_00_500k.json", what = "sp")
# View(states)
# Shape file - cb_2016_us_state_500k.shp
# states <- readOGR(dsn = "C:/DC/IFC/My Shiny apps/App US Adult Obesity",
# layer = "cb_2016_us_state_500k",
# encoding = "UTF-8", verbose = FALSE)
# Match data
obesity.map.2016 <- merge(states, obesity, by = "NAME")
class(obesity.map.2016)
View(obesity.map.2016)
# Create a palette
obesity.map.2016$Year.2016 <- as.numeric(as.character(obesity.map.2016
$Year.2016))
pal <- colorBin("Reds", c(22, 38), na.color = "#808080")
#, alpha = FALSE, reverse = FALSE)
# Create a popup
state_popup <- paste0("<strong>State: </strong>",
obesity.map.2016$NAME,
"<br><strong>% of adult obesity in 2016: </strong>",
obesity.map.2016$Year.2016)
# Create a map
leaflet(obesity.map.2016) %>%
addProviderTiles(providers$Stamen.TonerLite) %>%
setView(lng = -98.583, lat = 39.833, zoom = 4) %>%
addPolygons(color = "#444444", weight = 1,
# opacity = 0.5,
fillOpacity = 0.7,
fillColor = ~pal(obesity.map.2016$Year.2016),
popup = state_popup) %>%
addLegend("bottomright", pal = pal, values = ~obesity.map.2016$Year.2016,
opacity = 1,
title = "US Adult Obesity in 2016 by State (%)")