Shiny学习(五)||使用R脚本和数据

2020-05-26 22:01:52 浏览数 (1)

1.数据准备

建立一个census-app的目录,并在目录下新建data目录存储counties.rds文件,点击下载counties.rds

代码语言:javascript复制
#数据读入
counties <- readRDS("Documents/learnfile/shiny/test/census-app/data/counties.rds")
head(counties)

image.png

2.下载R脚本

helpers.R是一个R脚本,可以制作地图,并使用颜色显示的区域变化。在这个例子中,helpers.R将创建percent_map函数绘制counties.rds的数据。helpers.R 在此处下载。

image.png

helpers.R使用R中的mapsmapproj软件包。

代码语言:javascript复制
#安装
install.packages(c("maps", "mapproj"))
3.绘制地图

可以通过percent_map函数绘制一个choropleth地图。

代码语言:javascript复制
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文件

代码语言:javascript复制
# 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")
代码语言:javascript复制
runApp("census-app")

image.png

0 人点赞