我想创建一个简单的闪亮应用程序,如下所示。但是我希望美国县能够想象出州。您可以在下面找到数据集。有任何想法吗?我甚至可以接受其他的东西,而不是剧情,但我想要鼠标悬停能力。
# Grab air/water quality data from the EPA
url = "https://data.cdc.gov/api/views/cjae-szjv/rows.csv?accessType=DOWNLOAD"
dat <- read.csv(url, stringsAsFactors = FALSE)
# Colnames tolower
names(dat) <- tolower(names(dat))
dat$countyname <- tolower(dat$countyname)
# Wide data set, subset only what we need.
county_dat <- subset(dat, measureid == "296",
select = c("countyfips","statename", "countyname", "value", "unitname"))
# Rename columns to make for a clean df merge later.
colnames(county_dat) <- c("fips", "state", "county_name", "value", "unitname")
# Have to add leading zeos to any FIPS code that's less than 5 digits long to get a good match.
# I'm cheating by using C code. sprintf will work as well.
county_dat$fips <- formatC(county_dat$fips, width = 5, format = "d", flag = "0")
# Convert full state names to abbreviations for a clean df merge later.
county_dat$state <- state.abb[match(county_dat$state,state.name)]
library(shiny)
library(plotly)
ui <- fluidPage(
plotlyOutput("plot"),
verbatimTextOutput("click")
)
server <- function(input, output, session) {
output$plot <- renderPlotly({
# specify some map projection/options
g <- list(
scope = 'usa',
projection = list(type = 'albers usa'),
lakecolor = toRGB('white')
)
plot_ly(z = state.area, text = state.name, locations = state.abb,
type = 'choropleth', locationmode = 'USA-states') %>%
layout(geo = g)
})
output$click <- renderPrint({
d <- event_data("plotly_click")
if (is.null(d)) "Click on a state to view event data" else d
})
}
shinyApp(ui, server)
答案 0 :(得分:0)
以下是使用ggplotly
,geom_polygon
和maps::map_data
执行此操作的方法。处理艰难需要花费大量时间,因此您可能希望使用saveWidget
将结果图保存为HTML。该代码已根据?geom_polygon
的文档进行了改编。
library(ggplot2)
library(maps)
states <- map_data("county")
colordata <- data.frame(
subregion = unique(states$subregion),
## replace color with a vector of air quality measurements
color = rnorm(length(unique(states$subregion)))
)
choro <- merge(states, colordata, sort = FALSE, by = "subregion")
choro <- choro[order(choro$order), ]
p <- ggplot(choro, aes(long, lat)) +
geom_polygon(aes(group = group, fill = color))
p_ly <- ggplotly(p)
# display the plot
p_ly
# save the plot widget
htmlwidgets::saveWidget(p_ly, "plot.html")
您也可以使用
map('county', fill = TRUE, col = sample.int(20,1777,TRUE))
得到这个情节