【问题标题】:When plotting a subset of my data with renderPlotly and plot_ly the values of the xAxis are not correct使用 renderPlotly 和 plot_ly 绘制我的数据子集时,xAxis 的值不正确
【发布时间】:2018-08-14 07:48:21
【问题描述】:

我为不同国家/地区的不同指标设置了值。堆叠箱线图应该可以可视化我的数据。 我的目标是用户使用 selectInput 选择应该绘制哪些国家/地区。因此我使用子集。条形图仅针对所选国家/地区绘制,但 x 轴上的标签太多。看来,只要选择的国家/地区的价值为零,就会显示所有标签,直到一个国家的值大于零。

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

这是我的代码:

    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)
})

}

感谢您的建议! :)

【问题讨论】:

  • 您还应该包含运行代码所需的库
  • 抱歉,我使用了闪亮、闪亮的dashborad 和plotly。

标签: r shiny subset plotly action-button


【解决方案1】:

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

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)

【讨论】:

  • @Kali,太棒了!不要忘记接受答案:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 2017-01-03
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
相关资源
最近更新 更多