1.数据准备
建立一个census-app的目录,并在目录下新建data目录存储counties.rds文件,点击下载counties.rds
#数据读入
counties <- readRDS("Documents/learnfile/shiny/test/census-app/data/counties.rds")
head(counties)
2.下载R脚本
helpers.R
是一个R脚本,可以制作地图,并使用颜色显示的区域变化。在这个例子中,helpers.R
将创建percent_map
函数绘制counties.rds
的数据。helpers.R
在此处下载。
helpers.R
使用R中的maps
和mapproj
软件包。
#安装
install.packages(c("maps", "mapproj"))
3.绘制地图
可以通过percent_map函数绘制一个choropleth地图。
library(maps)
library(mapproj)
source("census-app/helpers.R")
counties <- readRDS("census-app/data/counties.rds")
percent_map(counties$white, "darkgreen", "% White")
4.建立app.R文件
将以下代码复制并粘贴到您的census-app目录下,新建一个app.R文件
# Load packages ----
library(shiny)
library(maps)
library(mapproj)
# Load data ----
counties <- readRDS("data/counties.rds")
# Source helper functions -----
source("helpers.R")
# User interface ----
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 logic ----
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(data, color, legend, input$range[1], input$range[2])
})
}
# Run app ----
shinyApp(ui, server)
5.保存app.R文件并运行runApp("census-app")
runApp("census-app")
欢迎关注~