如何将百分比添加到饼图中 R.Shiny

How to Add percentage into Pie chart R.Shiny

我是 R 编程的新手,我正在尝试在闪亮的应用程序上显示饼图,但我设法做到了 我在图表上显示百分比时遇到问题

这是代码

library("shiny")
dummy1=data.matrix(malevsfemal[1:3])
rownames(dummy1) = c("Male","Female")

# Use a fluid Bootstrap layout
ui = fluidPage(    

  # Give the page a title
  titlePanel("Male Vs Female According to each program"),

  # Generate a row with a sidebar
  sidebarLayout(      

    # Define the sidebar with one input
    sidebarPanel(
      selectInput("Program", "Program:", 
                  choices=colnames(dummy1))

    ),

    # Create a spot for the barplot
    mainPanel(

      plotOutput("Plot")  
    )

  )
)
# Rely on the 'WorldPhones' dataset in the datasets
# package (which generally comes preloaded).


# Define a server for the Shiny app
server = function(input, output) {


  # Fill in the spot we created for a plot
  output$Plot <- renderPlot({
    pct <- round(as.numeric(dummy1[,input$Program])/sum(as.numeric(dummy1[,input$Program]))*100)
    lbls <- paste(labels, pct) # add percents to labels
    lbls <- paste(lbls,"%",sep="") # ad % to labels
    # Render a barplot
    pie(dummy1[,input$Program], 
            main=input$Program,
            col=rainbow(2))
    legend("topright", c("Male", "Female"), cex=0.8,fill=rainbow(length(dummy1[,input$Program])))
  })
}
shinyApp(ui = ui, server = server)

数据集如下所示

mba sqlod msqbe
Male    281 79  44
Female  221 72  84

类型,矩阵 将不胜感激

第一次定义lbls时需要去掉labels,然后在pie函数中添加labels = lbls。这是完整的解决方案(但是,dummy1 现在是 data.frame,但您可以使用 as.matrix 函数轻松更改它):

library("shiny")

dummy1 <- data.frame("mba" = c(281, 221), "sqlod" = c(79,  72), "msqbe" = c(44, 84))
dummy1 <- as.data.frame.matrix(dummy1)
rownames(dummy1) <- c("Male","Female")

# Use a fluid Bootstrap layout
ui = fluidPage(    

  # Give the page a title
  titlePanel("Male Vs Female According to each program"),

  # Generate a row with a sidebar
  sidebarLayout(      

    # Define the sidebar with one input
    sidebarPanel(
      selectInput("Program", "Program:", 
                  choices=colnames(dummy1))

    ),

    # Create a spot for the barplot
    mainPanel(

      plotOutput("Plot")  
    )

  )
)
# Rely on the 'WorldPhones' dataset in the datasets
# package (which generally comes preloaded).


# Define a server for the Shiny app
server = function(input, output) {


  # Fill in the spot we created for a plot
  output$Plot <- renderPlot({
    pct <- round(as.numeric(dummy1[,input$Program])/sum(as.numeric(dummy1[,input$Program]))*100)
    lbls <- paste(pct) # add percents to labels
    lbls <- paste(lbls,"%",sep="") # ad % to labels
    # Render a barplot
    pie(dummy1[,input$Program], 
        main=input$Program,
        col=rainbow(2),
        labels = lbls)
    legend("topright", c("Male", "Female"), cex=0.8,fill=rainbow(length(dummy1[,input$Program])))
  })
}
shinyApp(ui = ui, server = server)