R-如何在Shiny中使用selectInput更改x并在ggplot renderPlot中填充变量? [英] R - How do I use selectInput in shiny to change the x and fill variables in a ggplot renderPlot?

查看:281
本文介绍了R-如何在Shiny中使用selectInput更改x并在ggplot renderPlot中填充变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个交互式的闪亮仪表板,该仪表板具有一个交互式绘图,您可以在其中更改绘图的值.我放入renderPlot中的代码块可以正常工作,所以我不明白为什么当我使用selectInput更改X和Fill变量时,计数未显示在y轴上.

I'm trying to make an interactive shiny dashboard that has an interactive plot where you can change the values of the plot. The code chunk that I'm putting inside of renderPlot works normally, so I don't understand why count isn't showing on the y axis when I use selectInput to change the X and Fill variables.

 inputPanel(
  selectInput('x', 'X', names(data)),
  selectInput('y', 'Y', names(data))
)

renderPlot({
    ggplot(data, aes(x = input$x)) +
  geom_bar(aes(fill = input$y), position = position_stack(reverse = TRUE)) +
 coord_flip() + 
 theme(legend.position = "top")
})

推荐答案

原因是input$xinput$ycharacter类.因此,使用aes_string

The reason is that the input$x and input$y are character class. So, instead of aes, use aes_string

renderPlot({
  ggplot(data, aes_string(x = input$x)) +
  geom_bar(aes_string(fill = input$y), position = position_stack(reverse = TRUE)) +
  coord_flip() + 
  theme(legend.position = "top")
})


具有data(mpg)

library(shiny)
library(ggplot2)


data(mpg)

ui <- fluidPage(
  inputPanel(
    selectInput('x', 'X', choices = c("manufacturer", "model", "year", "cyl", "class"),
          selected = "class"),
    selectInput('y', 'Y', choices = c( "trans", "fl", "drv"), 
  selected = "drv")
  ),

  mainPanel(plotOutput("outplot"))

)

server <- function(input, output) {

  output$outplot <- renderPlot({
    ggplot(mpg, aes_string(x = input$x)) +
      geom_bar(aes_string(fill= input$y), position = position_stack(reverse = TRUE)) +
      coord_flip() + 
      theme(legend.position = "top")
  })

}

shinyApp(ui = ui, server = server)

-输出

这篇关于R-如何在Shiny中使用selectInput更改x并在ggplot renderPlot中填充变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆