R闪亮的动态绘图

时间:2017-08-08 01:47:35

标签: r shiny plotly pie-chart

我有n列的表(所有列都是分类变量)。我想使用plotly和R-shiny为每列绘制饼图。

代码如下:

Server.R

df_data<-read.csv("file.csv")

df_data_num <- df_data[,sapply(df_data,is.numeric)]

var_list <- data.frame(colnames(df_data_num))


shinyServer(function(input, output) {

output$plots <- renderUI({
plot_output_list <- lapply(1:nrow(var_list), function(i) {
  plotname <- paste("plot", i, sep="")
  plotOutput(plotname, height = 280, width = 250)
})

do.call(tagList, plot_output_list)
})

for (i in var_list) {
  local({
  w = table(df_data_num$i ,exclude = NULL)
  sort(w)
  t= as.data.frame(w)
  plotname <- paste("plot", i, sep="")

  output[[plotname]] <- renderPlot({
    plot_ly(t, labels = "var1", values = "Freq", type = "pie") %>% 
    layout(title = paste("Plot for",my_i))

    })
  })
}
})

Ui.R

shinyUI(pageWithSidebar(

     headerPanel("Dynamic number of plots"),

     sidebarPanel(),
     mainPanel(
    # This is the dynamic UI for the plots
      uiOutput("plots")
    )
   ))

错误

Warning: Error in [[: no such index at level 1

Stack trace (innermost first):
    51: .subset2(x, "impl")$defineOutput

    50: [[<-.shinyoutput

    49: [[<- [C:\Users\Desktop/server.R#73]

    48: eval [C:\Users\Desktop/server.R#73]

    47: eval

    46: eval

    45: eval

    44: eval.parent

    43: local

    42: server [C:\Users\Desktop/server.R#64]

     1: runApp

     Error in private$.outputs[[name]] : no such index at level 1

请帮忙。

1 个答案:

答案 0 :(得分:1)

尝试这样的代码!

library(plotly)

# You have to import data in environment
df_data<-read.csv("file.csv")
df_data_num <- df_data[,sapply(df_data,is.numeric)]
df_data_num <- data.frame(df_data_num)

shinyUI(pageWithSidebar(
  headerPanel("Dynamic number of plots"), # Application title
  sidebarPanel(
     sliderInput(inputId = "colname",
                 label = "Choose a column",
                 min = 1,
                 max = n, # Choose the good number of column !
                 value = 1)
   ),
     mainPanel(
         plotlyOutput("plots") #If you want to use plotly, you need this.
   )
 )
)

shinyServer(function(input, output) {
   output$plots <- renderPlotly({  # Same thing
   p <- plot_ly(df_data_num, labels = ~input$colname, type = 'pie') %>%
     layout(title = 'Pie Chart')
   })
})