Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to open a dataset when I click on a section in pie chart?

Tags:

r

shiny

I want to create a pie chart and when I click on a section I should get a dataframe displayed. For example I might create the following pie chart:

# Create data for the graph.
x <- c(21, 62, 10, 53)
labels <- c("London", "New York", "Singapore", "Mumbai")

# Give the chart file a name.
png(file = "city.png")

# Plot the chart.
pie(x,labels)

enter image description here

Now lets say when I click on a slice such as 'london' I get the IRIS datset.

Solution i used:

library(shiny)
library(plotly)

df <- https://drive.google.com/file/d/1RT5AkCef4cehEaGelK0avbXAtck1f-Ap/view   #READ THIS DATA HERE
setDT(df)
dtnum <- df[ , .N, by="V3"]
dtnum2 <- df[ , .N, by="V2"]
ui <- fluidPage(
  
  plotlyOutput("myPlot"),
  plotlyOutput("myPlot2"),
  DTOutput("mydt")
  
)

server <- function(input, output, session) {
  
  observe({
    d <- event_data("plotly_click")
    print(d)
    if (is.null(d)) {
      df
    } else {
      output$mydt <- renderDT({
        df[V3 == d$customdata]
      })
    }
  })
  output$myPlot2 <- renderPlotly({
    plot_ly(dtnum2, labels = ~V2, values = ~N, type = 'pie', customdata = ~V2)
  }) 
  
  output$myPlot <- renderPlotly({
    plot_ly(dtnum, labels = ~V3, values = ~N, type = 'pie', customdata = ~V3)
  })
  
}

shinyApp(ui, server)
like image 374
ujjwal tyagi Avatar asked Dec 09 '25 08:12

ujjwal tyagi


1 Answers

Here is an example using shiny, plotly and DT.

To understand what's going on please check the plotly book on linking views with shiny and supplying custom data.

library(data.table)
library(plotly)
library(DT)
library(datasets)
library(shiny)

irisDT <- copy(iris)
setDT(irisDT)

ui <- fluidPage(
  plotlyOutput("myPlot"),
  DT::dataTableOutput("myTable")
)

server <- function(input, output, session) {
  output$myPlot <- renderPlotly({
    irisCountDT <- irisDT[,.N, by="Species"]
    fig <- plot_ly(irisCountDT, labels = ~Species, values = ~N, type = 'pie', source = "myPlotSource", customdata = ~Species)
  })
  
  myPlotEventData <- reactive({
    event_data(
      event = "plotly_click",
      source = "myPlotSource")
    })
  
  output$myTable <- DT::renderDataTable({
    datatable(irisDT[Species %in% myPlotEventData()$customdata[[1]]])
  })
}

shinyApp(ui, server)

result

Also check plotly's capabilities regarding crosstalk in this context.

like image 82
ismirsehregal Avatar answered Dec 11 '25 21:12

ismirsehregal