我想知道如何根据反应输入添加Geomlines。例如,如果我有一个checkboxGroupInput(下面)来选择保险类型,我们如何根据选定的保险类型向ggplot添加行。我还希望能够根据checkboxGroupInput添加多行进行比较。在UI方面,我们可以如下:
checkboxGroupInput(inputId = "Model",
label = h4("What kind of insurance do you use"),
choices = c("Compound" = "Compound", "Simple" = "Simple",
"Private" = "Private", "Complex" = "Complex"),
selected = "Private"
)
然后在服务器端
Mainplot <- renderPlot({
ggplot(df_norm,aes(x=ages)) +
# ADD GEOM_LINE HERE
)
})
我尝试根据输入创建一个对象,然后将其添加到绘图中,但这会在整个过程中产生错误。例如,
Line <- if ((input$Model == "Private") {"geom_line(aes(y=Private_line), size=0.5) +"} else { " "})
然后在情节中
Mainplot <- renderPlot({
ggplot(df_norm,aes(x=ages)) +
Line()
)
})
然而,这会产生错误“ggplot不知道如何处理RHS”。
感谢您提供的任何帮助, Conal
答案 0 :(得分:1)
您可以使用select
中的dplyr
来选择要显示的数据框列,gather
tidyr
个数据包,以便在数据框中收集它们并将它们分开按颜色:
library(ggplot2)
library(tidyr)
library(dplyr)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
checkboxGroupInput(inputId = "line",
label = h4("What would you like to plot?"),
choices = names(mtcars))
),
mainPanel(
plotOutput("plot")
)
)
)
server <- function(input, output) {
output$plot <- renderPlot({
validate(need(!is.null(input$line), 'Please tick a box to show a plot.'))
# 1. mpg is our fixed x-value
# 2. select variables of mtcars you need using select()
# 3. gather all selected variables in two columns: variable/value (but not mpg since that is the x value)
data <- gather(select(mtcars, "mpg", input$line), variable, value, -mpg)
# the plot, coloured by variable
ggplot(data, aes(x=mpg, y = value, colour = variable)) + geom_point()
})
}
shinyApp(ui, server)