繁体   English   中英

R - 带有 facet_wrap 的 ggplot 饼图

[英]R - ggplot pie chart with facet_wrap

我是否正确理解无法将 facet_wrap 与饼图 (ggplot + coord_polar) 一起使用?

library(ggplot2)
library(data.table)

c1 <- c(1,2,3,1,2,3)
c2 <- c("first","second","third","first","second","third")
c2 <- factor(c2, levels = c("first","second","third"))
c3 <- c(0.2,0.3,0.5,0.4,0.5,0.1)
c4 <- c("A","A","A","B","B","B")
c4 <- factor(c4, levels = c("A","B"))
cs <- data.frame(c1,c2,c3,c4)
ct <- data.table(cs)
ct[,midpoint:=cumsum(c3) - c3/2,by=c4]

colx <- c("blue","yellow","green")
ct[,colx:=colx,by=c4]

   c1     c2  c3 c4 midpoint   colx
1:  1  first 0.2  A     0.10   blue
2:  2 second 0.3  A     0.35 yellow
3:  3  third 0.5  A     0.75  green
4:  1  first 0.4  B     0.20   blue
5:  2 second 0.5  B     0.65 yellow
6:  3  third 0.1  B     0.95  green


vysg <- ggplot(ct, aes(x=1,y=c3,fill=c2)) + 
          geom_bar(stat="identity",width=2) + 
          coord_polar(theta='y')+
          theme(axis.ticks=element_blank(), axis.title=element_blank(), 
            axis.text.y = element_blank(), panel.grid  = element_blank(),
            axis.text.x = element_text(color=ct[,colx],size=15,hjust=0))+ 
        scale_y_continuous(breaks = ct[,midpoint], labels = ct[,c2])  + 
        scale_fill_manual(values=ct[,colx]) +
        scale_x_continuous(limits=c(-1,2.5))
vysg<-vysg+facet_wrap(~ c4)
vysg

在此处输入图片说明

份额似乎是正确的,但标签和它们的位置却不是。 有什么方法可以使用刻面还是必须使用网格?

而且我知道饼图不是最好的。

根据 cuttlefish44 有用的注释,代码看起来像这样

library(ggplot2)
library(data.table)

c1 <- c(1,2,3,1,2,3)
c2 <- c("first","second","third","first","second","third")
c2 <- factor(c2, levels = c("first","second","third"))
c3 <- c(0.2,0.3,0.5,0.4,0.5,0.1)
c4 <- c("A","A","A","B","B","B")
c4 <- factor(c4, levels = c("A","B"))
cs <- data.frame(c1,c2,c3,c4)
ct <- data.table(cs)
ct[,midpoint:=cumsum(c3) - c3/2,by=c4]

colx <- c("blue","yellow","green")
ct[,colx:=colx,by=c4]
ct

   c1     c2  c3 c4 midpoint   colx
1:  1  first 0.2  A     0.10   blue
2:  2 second 0.3  A     0.35 yellow
3:  3  third 0.5  A     0.75  green
4:  1  first 0.4  B     0.20   blue
5:  2 second 0.5  B     0.65 yellow
6:  3  third 0.1  B     0.95  green


vysg <- ggplot(ct, aes(x=1,y=c3,fill=c2)) + 
          geom_bar(stat="identity",width=2) + 
          coord_polar(theta='y')+
        theme(axis.ticks=element_blank(), axis.title=element_blank(),axis.text.y = element_blank(),axis.text.x = element_blank(), panel.grid  = element_blank())+
        geom_text(aes(x = 2.5, y = midpoint, label = c2, colour = I(colx)))+
        scale_x_continuous(limits=c(-1,2.5))+
        scale_fill_manual(values=colx)
vysg<-vysg+facet_wrap(~ c4)
vysg

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM