前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >R海拾遗-shiny3

R海拾遗-shiny3

作者头像
火星娃统计
发布2020-09-15 15:28:38
5000
发布2020-09-15 15:28:38
举报
文章被收录于专栏:火星娃统计火星娃统计

shiny 学习3

概述

正文

使用R脚本和带入数据

数据集: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文件夹中 代码

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

结果

代码语言:javascript
复制
# 接下来使用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)

结果

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-07-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 火星娃统计 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • shiny 学习3
    • 概述
      • 正文
        • 使用R脚本和带入数据
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档