2016-02-20 242 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。你用同样的东西吗? –