2016-02-20 240 views
2

我想製作一個圖形與此類似:百分比標籤

relative frequency

我開始使用此代碼:

library(ggplot2) 
library(scales) #needed for labels=percent 

var1 <- sample(0:20,78,replace = TRUE) 

var2 <- cut(var1, breaks = seq(0,20,5),include.lowest = TRUE) 
df<-as.data.frame(var2) 

ggplot(df, aes(x= var2)) + 
     geom_bar(aes(y = ..prop..,group=1),fill="dodgerblue3")+ 
     scale_y_continuous(labels=percent)+ 
     labs(x = NULL,y = NULL)+ 
     theme(axis.ticks.x = element_blank(), 
      axis.text = element_text(size=7)) 

但我不能把標籤中劇情。

我試圖按照this example

ggplot(df, aes(x= var2, group=1)) + 
    geom_bar(aes(y = ..density..)) + 
    geom_text(aes(label = format(100*..density.., digits=2, drop0trailing=TRUE), 
       y= ..density..), stat= "bin", vjust = -.5) + 
    scale_y_continuous(labels=percent) 

但我得到這個錯誤(我用GGPLOT2版本2.0.0):

Error: StatBin requires a continuous x variable the x variable is discrete. Perhaps you want stat="count"?

最後我做了這個代碼的情節:

per <- df %>% group_by(var2) %>% summarise(freq = n()/nrow(df)) 

ggplot(data=per, aes(x=var2,y=freq)) + 
     geom_bar(stat="identity",fill="dodgerblue3")+ 
     geom_text(aes(label=percent(freq)),vjust=1.5,colour="white")+ 
     scale_y_continuous(labels=percent)+ 
     labs(x = NULL,y = NULL)+ 
     theme(axis.ticks.x = element_blank(), 
      axis.text = element_text(size=7)) 

然而,是否有可能使它像this example,沒有nee d爲per dataframe並直接在ggplot中?

回答

3

你可以試試這個,它取自here並自定義。

ggplot(df, aes(factor(var2))) + 
    geom_bar(fill="dodgerblue3")+ 
    labs(x = NULL,y = NULL)+ 
    stat_bin(aes(label = paste(prop.table(..count..) * 100, "%", sep = "")), 
      vjust = 1, geom = "text", position = "identity", color ="white") 

,並提供:enter image description here

編輯:

在新ggplot 2.0.X版本,stat_count應使用不stat_bin。從help

stat_count, which counts the number of cases at each x posotion, without binning. It is suitable for both discrete and continuous x data, whereas stat_bin is suitable only for continuous x data.

ggplot(df, aes(factor(var2))) + 
     geom_bar(fill="dodgerblue3")+ 
     labs(x = NULL,y = NULL)+ 
     stat_count(aes(label = paste(prop.table(..count..) * 100, "%", sep = "")), 
       vjust = 1, geom = "text", position = "identity", color ="white") 
+0

感謝。但它沒有奏效。至少對於我來說。我錯過了一些事情,因爲它適合你。但我已經嘗試過你的代碼,我已經obteined同樣的錯誤'錯誤:StatBin需要一個連續的x變量x變量是離散的。也許你想要stat =「count」?'。我不知道我做錯了什麼。 –

+0

@ ChristianGonzalez-Martel奇怪。嘗試R/Rstudio(不保存工作區圖像的課程)並重試? – RHA

+0

它還沒有工作。也許問題是ggplot2的版本。我使用2.0.0。你用同樣的東西嗎? –