How to change labels in plot_ly pie chart given input in R shiny

I am trying to create a pie chart based on a user’s input. Without adding the "labels" argument in the plotly function, the pie chart renders upon different inputs but I would like the labels added. When I try to use a variable for my labels, the pie chart just comes out at 100% all one value (I am assuming this is because it isn’t recognizing the variable as a string? Is there a way the labels can also change with the input?

I have tried using labels=~input$cat which does not work (fig2 <- plot_ly(fig, ~labels=input$cat, values = ~n, type = ‘pie’).

library(shiny)
library(ggplot2)
library(dplyr)
library(plotly)

student_name <- c("Ally","Sam","Bailey","Aaron","Emily","Zack")
col <- c("Red","Red","Red","Green","Green","Blue,")
subject <-c("math","math","science","art","art","music")

df <- data.frame(student_name, col, subject)

ui <- fluidPage(
    selectInput("cat", "Category", choices = c("student_name","col","subject"), selected = "col"),
    plotlyOutput("oppie")
)

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

  output$oppie <- renderPlotly({
      
      #PIE CHART
      fig <- df %>%
        group_by(across(input$cat)) %>%
        summarise(n=n())
      
      fig2 <- plot_ly(fig, values = ~n, type = 'pie')
      #labels =~subject
      #labels = ~input$cat

    })

  
}

shinyApp(ui, server)

What I currently have:

enter image description here

What I want:

enter image description here

What I get if I try to use labels=~input$cat:

enter image description here

>Solution :

The issue is that input$cat is a character string. One option to map the column whose name is stored in input$cat on the labels attribute would be to rename your column like so:

library(shiny)
library(dplyr, warn=FALSE)
library(plotly, warn=FALSE)
#> Loading required package: ggplot2

student_name <- c("Ally", "Sam", "Bailey", "Aaron", "Emily", "Zack")
col <- c("Red", "Red", "Red", "Green", "Green", "Blue,")
subject <- c("math", "math", "science", "art", "art", "music")

df <- data.frame(student_name, col, subject)

ui <- fluidPage(
  selectInput("cat", "Category", choices = c("student_name", "col", "subject"), selected = "col"),
  plotlyOutput("oppie")
)

server <- function(input, output, session) {
  output$oppie <- renderPlotly({
    fig <- df %>%
      rename(cat = input$cat) %>%
      group_by(cat) %>%
      summarise(n = n())

    fig2 <- plot_ly(fig, values = ~n, labels = ~cat, type = "pie")
  })
}
shinyApp(ui, server)
#> 
#> Listening on http://127.0.0.1:8826

Leave a Reply