【问题标题】:Adding legend to pie chart that is wrapped by ggplot将图例添加到由 ggplot 包装的饼图
【发布时间】:2020-10-12 18:17:59
【问题描述】:

我对 R 很陌生,需要一些支持来使用 pie 函数。

我需要返回一个 ggplot,所以我用这个包装了 pie 函数。 输出是预期的饼图,唯一的问题是,我还想在它旁边有一个图例。

我需要返回一个 ggplot 但不能将它与图例函数结合起来。有人可以提供一些指导吗

【问题讨论】:

    标签: r ggplot2 r-markdown legend pie-chart


    【解决方案1】:

    这和标准的ggplot一样容易,然后你就可以免费获得图例:

    library(ggplot2)
    
    slices <- c(10, 12, 4, 5, 8)
    countries <- c("US", "Japan", "UK", "Germany", "France")
    pct    <- round(slices/sum(slices)*100)
    lbls   <- paste(pct, "%", sep="") 
    lbl_y  <- 100 - (c(13, 42.5, 62, 73.5, 90))
    df     <- data.frame(slices, pct, lbls, countries = factor(countries, levels = countries))
    
    ggplot(df, aes(x = 1, y = pct, fill = countries)) + 
      geom_col(position = "stack", orientation = "x") + 
      geom_text(aes(x = 1, y = lbl_y, label = lbls), col = "white") +
      scale_fill_discrete(breaks = countries) +
      coord_polar(theta = "y", direction = -1) + 
      theme_void()
    

    reprex package (v0.3.0) 于 2020 年 6 月 22 日创建

    【讨论】:

      【解决方案2】:

      你可以试试这样的:

      library(ggplot2)
      library(dplyr)
      #Data
      data <- data.frame(slices = c(10, 12, 4, 5, 8),
                         countries = c("US", "Japan", "UK", "Germany", "France"),
                         stringsAsFactors = F)
      #Create variable
      data <- data %>% 
        mutate(per=slices/sum(slices)) %>% 
        arrange(desc(countries))
      data$label <- scales::percent(data$per)
      #Plot
      ggplot(data=data)+
        geom_bar(aes(x="", y=per, fill=countries), stat="identity", width = 1)+
        coord_polar("y", start=0)+
        theme_void()+
        geom_text(aes(x=1, y = cumsum(per) - per/2, label=label))+
        ggtitle("pie chart example")
      

      【讨论】:

        【解决方案3】:

        使用 ggplot2

        library(tidyverse)
        slices <- c(10, 12, 4, 5, 8)
        pct <- round(slices/sum(slices)*100)
        lbls <- paste(pct, "%", sep="") 
        countries <- c("US", "Japan", "UK", "Germany", "France")
        
        #convert your data to a data frame
        df <- data.frame(slices, pct, countries)
        
        #create a stacked bar plot
        barPlot <- ggplot(data = df, mapping = aes(x = 1, y = pct, fill = countries)) +
        geom_bar(position = 'fill', stat = 'identity')
        
        #change to coordinates to polar
        piePlot <- barPlot + 
          coord_polar("y", start = 0) +
          theme_void()+
          theme(legend.position = 'top')
        piePlot
        

        【讨论】:

          猜你喜欢
          • 2021-01-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-01
          • 2018-07-19
          相关资源
          最近更新 更多