在Shiny中设置数据以创建交互式ggplot条形图

时间:2016-01-22 13:19:08

标签: r ggplot2 shiny

我正在尝试构建我的第一个闪亮的应用程序,让用户可以在哥本哈根探索不同类型的停车违规行为。但是我很难根据用户输入将数据子集化为plottet - 基本上我正在尝试创建下图中的交互式版本,用户可以在其中选择type_1,type_2等。

#example data
df <- data.frame(c('a', 'b', 'c', 'd', 'e', 'f', 'g'), c(rep_len(55, 5), 0, 44),c(rep_len(12, 5), 6, 6), c(0, 2, 0, 3, 0, 7, 8), c(0, 0, 4, 0, 8, 5, 3), c(5, 0, 6, 0, 11,12, 9))
names(df) <- c("street", "type_1", "type_2", "type_3", "type_4", "type_5")

#Example of static plot that i'm trying to make interactive
ggplot(subset(df, type_5 > 5))+geom_bar(aes(x=reorder(street,type_5), y=type_5),stat = "identity")+coord_flip()+xlab("Streetname")

enter image description here

我的ui.R和server.R如下。我的原始数据有超过2000个街道名称,这就是为什么我试图将数据分组以仅包含违反type_x的违规行为&gt;一些门槛

# Define the overall UI
ui <- shinyUI(

# Use a fluid Bootstrap layout
fluidPage(    

# Give the page a title
titlePanel("Parking violations"),

# Generate a row with a sidebar
sidebarLayout(      

  # Define the sidebar with one input
  sidebarPanel(
    selectInput("type", "Type of violation:", 
                choices=colnames(df), selected = "type_1" ),
    hr(),
    helpText("Data from Parking Copenhagen")
  ),

  # Create a spot for the barplot
  mainPanel(
    plotOutput("pplot")  
  )

)
)
)



# Define a server for the Shiny app
server <- shinyServer(function(input, output) {

  #Subset the data based on user input
  p.df <- reactive({
    subset(df, input$type > 5)
  })  


  # Fill in the spot we created for a plot
  output$pplot <- renderPlot({

    pdat.df <- p.df()

    # Render a barplot
    p <- ggplot(pdat.df, aes(x=pdat.df$street, y=input$type)) + geom_bar(stat = "identity")+coord_flip()

    print(p)

  })
})

shinyApp(ui=ui, server = server)

下面的结果并不是我想要的。我已经尝试了shiny not displaying my ggplot as I'd expect.中建议的选项,但在ggplot()(如我的静态示例中)或geom_bar()

中的子集化方面没有运气

非常感谢任何建议。谢谢!

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为您需要更改subset(df, input$type > 5)

上的return( df[df[input$type]>5,])

因为输入返回charactersubset无法将其解释为colname 例如(包含您的数据)

subset(df,"type_1">5)
    #  street type_1 type_2 type_3 type_4 type_5
    #1      a     55     12      0      0      5
    #2      b     55     12      2      0      0
    #3      c     55     12      0      4      6
    #4      d     55     12      3      0      0
    #5      e     55     12      0      8     11
    #6      f      0      6      7      5     12
    #7      g     44      6      8      3      9

df[df["type_1"]>5,]
    #  street type_1 type_2 type_3 type_4 type_5
    #1      a     55     12      0      0      5
    #2      b     55     12      2      0      0
    #3      c     55     12      0      4      6
    #4      d     55     12      3      0      0
    #5      e     55     12      0      8     11
    #7      g     44      6      8      3      9

(第6行子目录)

我看不到你的闪亮版本的重新排序 试试

pdat.df <- p.df()
pdat.df$street=reorder(pdat.df$street,pdat.df[[input$type]])

和@MLavoie告诉

aes_string(x="street", y=input$type)