闪亮的分类数据可视化问题

问题描述

我想可视化数据类别,但是我无法通过下面的代码得到想要的东西。当我想将数据分为几类时,它将对它进行整体评估。我无法对图表进行分类。我在做什么错了?

library(shiny)
library(ggplot2)

ui <- fluidPage(

titlePanel("shiny demo"),sidebarLayout(

   sidebarPanel(
  
  fileInput(inputId = "file",label = "choose file",multiple = F),selectInput("p","variable1",choices = c("sex","smoke","happines","city","work")),selectInput("q","variable2",choices = c("hopefulnes","happines"))),mainPanel(
  tabsetPanel(
    
    tabPanel(title = "Data",tableOutput("data_out")),tabPanel(title = "Bar",plotOutput("barp"))
    
      )
    )
  )
)
server <- function(input,output,session) {

 data <- reactive({
 req(input$file)

 df=read.csv(input$file$datapath,sep = ";",header = T)

 })
 output$data_out <- renderTable({
 data() 
 })
  
 output$barp <- renderPlot({      
 ggplot(data(),aes(input$p,..count..)) + geom_bar(aes(fill = input$q),position = "dodge")  
 })

}
shinyApp(ui,server)

数据;

id  sex   smoke happines     hopefulness   work city
1   man   yes   very happy   very hopeful   yes   A
2   man   no    very happy   very hopeful   yes   A
3   man   no    unstable     not hopeful    no    C
4   woman no    unstable     not hopeful    yes   A
5   woman no    unstable     not hopeful    yes   B
6   man   yes   very happy   hopeful        yes   C
7   woman yes   happy        unstable       no    D
8   man   yes   not happy    not hopeful    yes   A
9   woman no    not happy    unstable       yes   B
10  man   no    very happy   very hopeful   yes   D

错误代码

输入asJSON(keep_vec_names = TRUE)的是一个命名向量。在jsonlite的未来版本中,将不支持此选项,命名向量将转换为数组而不是对象。如果要输出JSON对象,请改用命名列表。请参阅?toJSON。

感谢帮助

解决方法

设置

selectInput()以输出字符串,而设置aes()以期望命名列。如果您从input$p中选择“烟雾”,并从input$q中选择“幸福”,则这将作为"smoke""happiness"而不是smoke进入函数happiness。因此,它将像您发送此函数一样进行绘制:

ggplot(df,aes("smoke",..count..)) +
  geom_bar(aes(fill = "happiness"),position = "dodge")

enter image description here

要处理selectInput()的字符串输出,应使用aes_string()代替aes()。您需要将..count..更改为"..count..",但是它将像您要求评估以下代码块一样工作:

ggplot(df,aes_string("smoke","..count..")) +
  geom_bar(aes_string(fill = "happiness"),position = "dodge")

enter image description here

您可以执行此操作的另一种方法是使用aes()进行维护,但只需将input$pinput$q中的字符串作为变量名来求值。您可以正常使用get()进行此操作,因此我相信它也可以在您的应用程序中使用。在这种情况下,您不必将..count..更改为"..count.."

# yields the same plot as above
ggplot(df,aes(get("smoke"),..count..)) +
  geom_bar(aes(fill = get("happiness")),position = "dodge")