0

我有不同国家不同指标的值。堆叠箱线图应该可以可视化我的数据。我的目标是用户使用 selectInput 选择应该绘制哪些国家/地区。因此我使用子集。条形图仅针对所选国家/地区绘制,但 x 轴上的标签太多。It seems, that whenever a chosen country has a value of zero, all the labels are shown until a country has a value greater than zero.

为了检查数据是否被正确过滤,我还打印了一个表格。

这是我的代码:

    Country <- c("Germany", "France", "UK", "Italy","Spain","US", "Canada","China","India","Japan")
data <- data.frame(country=Country,value=c(4,1,0,0,2,5,2,7,3,1,3,1,0,0,1,5,7,2,2,3),Ind=c(rep("1", times=10),rep("2", times=10)))



UI <- dashboardPage(

dashboardHeader(),
  dashboardSidebar(
    sidebarMenu(
      menuItemOutput("menu"),

      menuItem(selectInput(inputId = "ChooseCountry", label = "Choose Countries", Country,selected=list("India", "China"), multiple = T))
    )
  ),

  dashboardBody("barchart",
          fluidRow(
            box(plotlyOutput("step1"), width = 12),
          fluidRow(
            box(tableOutput("Table"), width=12)
          )

          ))

)




Server <- function(input, output, session) {



output$step1 <- renderPlotly({
  Data <- subset(data, country %in% input$ChooseCountry)
  plot_ly(data = Data, 
          x = ~country, y = ~value, color = ~Ind, type = "bar") %>%
    layout(barmode="stack")
})


output$Table <- renderTable( {
  Data <- subset(data, country %in% input$ChooseCountry)
})

}

谢谢你的建议!:)

4

1 回答 1

0

您可以删除未使用的级别。试试这个:

Server <- function(input, output, session) {
  output$step1 <- renderPlotly({
    Data <- subset(data, country %in% input$ChooseCountry)
    Data[] <- lapply(Data, function(x) if(is.factor(x)) factor(x) else x)
    plot_ly(data = Data, 
            x = ~country, y = ~value, color = ~Ind, type = "bar") %>%
      layout(barmode="stack")
  })
  output$Table <- renderTable( {
    Data <- subset(data, country %in% input$ChooseCountry)
  })
}

shinyApp(ui = UI,server = Server)
于 2018-03-06T13:27:00.063 回答