代码之家  ›  专栏  ›  技术社区  ›  Jack Armstrong

在一个绘图中绘制带标签的多个饼图

  •  0
  • Jack Armstrong  · 技术社区  · 6 年前

    前几天我遇到了这个问题,并试图为自己重新创造它。 ggplot, facet, piechart: placing text in the middle of pie chart slices . 我的数据是在一个非常相似的格式,但遗憾的是,接受的答案没有帮助,因此我重新张贴。

    我基本上是想用我自己的数据创建一个被接受的答案,但我遇到的问题是 coord_polar does not support free scale test_pie

    我尝试使用第二个版本的答案,与ddplyr版本,但我也没有得到我想要的输出。使用第二个答案: test_pie2

    显然,这些都没有达到预期的效果。我更愿意创建一个大小饼图,但仅以四个为例,如下所示: desired_pie . 这是我在excel中做的,但是只有一个图例,没有背景网格。

    代码

    title<-c(1,1,2,2,3,3,4,4,5,5,6,6)
    type<-c('A','B','A','B','A','B','A','B','A','B','A','B')
    value<-c(0.25,0.75,0.3,0.7,0.4,0.6,0.5,0.5,0.1,0.9,0.15,0.85)
    
    piec<-data.frame(title,type,value)
    library(tidyverse)    
    
    p1<-ggplot(data = piec, aes(x = "", y = value, fill = type)) + 
      geom_bar(stat = "identity") +
      geom_text(aes(label = value), position = position_stack(vjust = 0.5)) +
      coord_polar(theta = "y") 
      #facet_grid(title ~ ., scales = "free")
    p1
    
    
    piec <- piec %>% group_by(title) %>% mutate(pos=cumsum(value)-0.5*value)
    p2<-ggplot(data = piec) + 
      geom_bar(aes(x = "", y = value, fill = type), stat = "identity") +
      geom_text(aes(x = "", y = pos, label = value)) +
      coord_polar(theta = "y") 
      #facet_grid(Channel ~ ., scales = "free") 
    p2
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   pogibas    6 年前

    您不必为以下对象提供不同的y值: geom_text geom_bar (使用 y = value 几何图形文本 scales 从侧面看。

    library(ggplot2)
    
    title<-c(1,1,2,2,3,3,4,4,5,5,6,6)
    type<-c('A','B','A','B','A','B','A','B','A','B','A','B')
    value<-c(0.25,0.75,0.3,0.7,0.4,0.6,0.5,0.5,0.1,0.9,0.15,0.85)
    piec<-data.frame(title,type,value)
    
    ggplot(piec, aes("", value, fill = type)) + 
        geom_bar(stat = "identity", color = "white", size = 1) +
        geom_text(aes(label = paste0(value * 100, "%")), 
                  position = position_stack(vjust = 0.5), 
                  color = "white", size = 3) +
        coord_polar(theta = "y") +
        facet_wrap(~ title, ncol = 3) +
        scale_fill_manual(values = c("#0048cc", "#cc8400")) +
        theme_void()
    

    enter image description here