SHILY:将输入$var传递给ggplot2中的AES() [英] Shiny: passing input$var to aes() in ggplot2
本文介绍了SHILY:将输入$var传递给ggplot2中的AES()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一款闪亮的应用程序,根据年龄(年龄)或性别(性别)类别绘制变量Val的密度图表。用户在下拉菜单中选择"性别"或"年龄",我一直在尝试使用gglot和ggvis中的fill = input$Group_select
。
在gglot中:
output$plot <- renderPlot(ggplot(gdat[gdat$GFR==input$GFR_select,]) +
aes(x= VAL, fill=input$Group_select) +
geom_density(adjust=input$slider1))
edit:正如docendo指出的,可以使用aes_string:
为gglot修复此问题output$plot <- renderPlot(ggplot(gdat[gdat$GFR==input$GFR_select,]) +
aes(x= VAL) +
geom_density(adjust=input$slider1, aes_string(fill=input$Group_select))):
在ggvis中:
gvis <- reactive(subset(gdat, GFR==input$GFR_select) %>%
ggvis(x = ~VAL) %>% group_by_(input$Group_select) %>%
layer_densities(adjust = input$slider1) %>%
add_axis("y", title = "Density", ticks="none") %>%
scale_numeric("x", domain = c(0, 230)) )
gvis %>% bind_shiny("ggvis", "ggvis_ui")
解决方案:使用as.name(输入$Group_SELECT)将正确呈现图形!
这是呈现的内容:Imgur link to shiny output。有趣的是,GROUP_BY_似乎正确解释了输入$GROUP_SELECT,而输入$GROUP_SELECT在fill=input$Group_select
关于如何正确渲染绘图有什么建议吗?
以下是完整的闪亮代码:
ui.R
library(shiny)
library(ggplot2)
library(dplyr)
library(ggvis)
shinyUI(fluidPage(
titlePanel("eGFR in the ARIC study"),
sidebarPanel(
selectInput("Group_select",
label=h3("By-Variable"),
choices=c("AGE","SEX","ALL"),
selected="SEX"),
selectInput("GFR_select",
label=h3("Creatinine Measure"),
choices=c("BOTH", "CREATININE", "CYSTATIN", "MDRD"),
selected="MDRD"),
sliderInput("slider1", label = h3("Bandwith Adjustment"),
min = 0.5, max = 4, value = 1)
),
mainPanel(
uiOutput("ggvis_ui"),
ggvisOutput("ggvis"),
plotOutput("plot")
)
))
server.R
library(shiny)
source("helpers.R")
shinyServer(function(input, output) {
gvis <- reactive(subset(gdat, GFR==input$GFR_select) %>%
ggvis(x = ~VAL, fill = ~input$Group_select) %>% group_by_(input$Group_select) %>%
layer_densities(adjust = input$slider1) %>%
add_axis("y", title = "Density", ticks="none") %>%
scale_numeric("x", domain = c(0, 230)) )
gvis %>% bind_shiny("ggvis", "ggvis_ui")
output$plot <- renderPlot(ggplot(gdat[gdat$GFR==input$GFR_select,]) +
aes(x= VAL, fill=input$Group_select) +
geom_density(adjust=input$slider1))
})
推荐答案
我不确定这是否仍是一个悬而未决的问题,但aes_string
的替代方案是将字符串转换为符号:
library(ggplot2)
# usually you can put all the shared aesthetics in the first line
ggplot(mtcars, aes(mpg, hp, colour = cyl)) +
geom_point()
# when the input is a string, you can use aes_string(), but you'd
# have to enter the string var separately, or change all vars..
input <- "cyl"
ggplot(mtcars, aes(mpg, hp)) +
geom_point(aes_string(colour = input))
# or
# ggplot(mtcars, aes_string("mpg", "hp", colour = input)) +
# geom_point()
# you can put the converted string var in the normal aes()
ggplot(mtcars, aes(mpg, hp, colour = !!as.symbol(input))) +
geom_point()
# note: as.name() and as.symbol() are aliases
由reprex package(v0.2.0)创建于2018-11-05。
这篇关于SHILY:将输入$var传递给ggplot2中的AES()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文