R - ggplot饼图与facet_wrap

时间:2016-10-17 14:17:08

标签: r ggplot2

我是否理解正确无法将饼图(ggplot + coord_polar)完全用于facet_wrap?

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

enter image description here

股票似乎是正确的,但标签及其位置不是。 有没有办法如何使用刻面或是否有必要使用网格?

我知道饼图不是最好的。

1 个答案:

答案 0 :(得分:1)

根据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

enter image description here