0

I'm trying to build a donut plot in my shiny app that uses plotly, similar to this one from another question). However' my plot never appears. I've researched other answer (such as this one, this one, and this one), but they don't get me closer to my answer.

What am I doing wrong?

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

my_colors <- c("#00A3AD", "#FF8200", "#753BBD")

ui <- fluidPage(
    sidebarLayout(
        sidebarPanel(
            
        ),
        mainPanel(
            fluidRow(
                plotlyOutput("count_by_person")

            ))
    ))
server <- function(input, output) {
    
    
    output$count_by_person <- renderPlotly({
        
        data <- tibble(name = c("Justin", "Corey", "Sibley"),
                       n = c(1, 3, 6),
                       prop = c(.1, .3, .6))

        plot_ly(data, aes(x = 2, y = prop, fill = name)) +
            geom_bar(stat = "identity", color = "white") +
            coord_polar(theta = "y", start = 0)+
            geom_text(aes(y = lab.ypos, label = paste0("n = ", n, ", \n", prop, "%")), color = "white")+
            scale_fill_manual(values = my_colors) +
            theme_void() +
            xlim(.5, 2.5)
    })
    
}
shinyApp(ui, server)
J.Sabree
  • 2,280
  • 19
  • 48
  • Try with `ggplot(...)` instead of `plot_ly` and convert your plot afterwards to a plotly object using `plotly::ggplotly`. Unfortunately I'm afraid ggplotly fails to convert your ggplot donut to a plotly donut. – stefan Jun 16 '21 at 20:48

1 Answers1

0

Always try and reproduce the image outside of shiny before bringing it into your application

data <- tibble(name = c("Justin", "Corey", "Sibley"),
                       n = c(1, 3, 6),
                       prop = c(.1, .3, .6))

plot_ly(data, aes(x = 2, y = prop, fill = name)) +
            geom_bar(stat = "identity", color = "white") +
            coord_polar(theta = "y", start = 0)+
            geom_text(aes(y = lab.ypos, label = paste0("n = ", n, ", \n", prop, "%")), color = "white")+
            scale_fill_manual(values = my_colors) +
            theme_void() +
            xlim(.5, 2.5)

If you run the code in your script, you'll see it returns null because you're trying to use plotly with ggplot syntax

Try starting with the code below to generate a basic donut chart and reading the plotly documentation here to modify it:

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

my_colors <- c("#00A3AD", "#FF8200", "#753BBD")

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      
    ),
    mainPanel(
      fluidRow(
        plotlyOutput("count_by_person")
        
      ))
  ))
server <- function(input, output) {
  
  
  output$count_by_person <- renderPlotly({
    
    data <- tibble(name = c("Justin", "Corey", "Sibley"),
                   n = c(1, 3, 6),
                   prop = c(.1, .3, .6))
    
    data %>% 
      plot_ly(values=~prop) %>%
      add_pie(hole = 0.6)

  })
  
}
shinyApp(ui, server)

Marshall K
  • 302
  • 1
  • 8