数据集:counties.rds是美国每个县的人口统计数据集,由UScensus2010 收集。需要另外下载 https://shiny.rstudio.com/tutorial/written-tutorial/lesson5/census-app/data/counties.rds 下载后是一个rds文件,需要在之前介绍的app文件夹中建立data文件,然后将数据集移动到data中 脚本:help.R: https://shiny.rstudio.com/tutorial/written-tutorial/lesson5/census-app/helpers.R 下载之后将脚本放入app文件夹中 代码
setwd("D:\\360MoveData\\Users\\cmusunqi\\Documents\\GitHub\\R_and_python\\R")
counties <- readRDS("census-app/data/counties.rds")
head(counties)
# 包含州的名字和人口构成
# 安装地图包
# install.packages(c("maps", "mapproj"))
# maps和mapproj是脚本使用到的包
library(maps)
library(mapproj)
# 使用预先写好的脚本绘制地图
source("census-app/helpers.R")
counties <- readRDS("census-app/data/counties.rds")
# 各县的数据绘制成地形图。这里用深绿色表示各县白人居民的比例。
percent_map(counties$white, "darkgreen", "% White")
结果
# 接下来使用shiny控件
library(shiny)
ui <- fluidPage(
titlePanel("censusVis"),
sidebarLayout(
sidebarPanel(
helpText("Create demographic maps with
information from the 2010 US Census."),
selectInput("var",
label = "Choose a variable to display",
choices = c("Percent White", "Percent Black",
"Percent Hispanic", "Percent Asian"),
selected = "Percent White"),
sliderInput("range",
label = "Range of interest:",
min = 0, max = 100, value = c(0, 100))
),
mainPanel(plotOutput("map"))
)
)
# Server
# 通过server代码连接输出字段
server <- function(input, output) {
# 定义输出图
output$map <- renderPlot({
data <- switch(input$var,
"Percent White" = counties$white,
"Percent Black" = counties$black,
"Percent Hispanic" = counties$hispanic,
"Percent Asian" = counties$asian)
color <- switch(input$var,
"Percent White" = "darkgreen",
"Percent Black" = "black",
"Percent Hispanic" = "darkorange",
"Percent Asian" = "darkviolet")
legend <- switch(input$var,
"Percent White" = "% White",
"Percent Black" = "% Black",
"Percent Hispanic" = "% Hispanic",
"Percent Asian" = "% Asian")
# 这里是绘图的函数
percent_map(var = data, color , legend, max =input$range[1] ,input$range[2])
})}
shinyApp(ui, server)
结果