2016-10-17 71 views
0

對於餅圖(ggplot + coord_polar),我是否可以完全使用facet_wrap?R - 帶facet_wrap的ggplot餅圖

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

股份似乎正確的,但在標籤和它們的位置都沒有。 有沒有辦法如何使用facetting或是否有必要使用網格?

而且我知道餅圖不是最好的。

+2

這將是容易使用'geom_text',如'+ geom_text(AES(X = 2.5,Y =中點,標籤= c2,顏色= c2))' – cuttlefish44

+0

謝謝。我已將您的改進解決方案作爲答案發布。它完美的作品。如果你想,自己發佈,我會刪除我的版本。只是想顯示結果。 – Martin

+1

你不必這樣做。您可以通過使用更大的值(如下面的xxx,scale_x_continuous(limits = c(-1,xxx))和geom_text(aes(x = xxx,y = ...))來改變餅圖和標籤之間的距離。 。您可以使用'geom_text(aes(...),fontface =「bold」)'加粗字體 – cuttlefish44

回答

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