ggplot2:如何在百分比条形图上添加百分比或计数标签?非数字数据

时间:2016-09-02 10:49:13

标签: r ggplot2 label

抱歉我的英语能力差。我会写很多语法拼写错误。我为它道歉。

我有一些非数字数据,如:

#Used library
library(ggplot2)
library(scales)

#Definition of data
graph<-cbind.data.frame(
    sample(c("FI", "FA","FC"), 100, replace = TRUE),
    sample(c("Rep","Dip"),100, replace=TRUE)
)
names(graph)<- c("RegimeInscription","repondant")

我照看这样的图表:来自graph barplot position fill with percent value in barthis question 我按照说明进行操作,但它对X轴上的离散数据无效。

#Some var
theme_barre <- theme_bw()+
  theme(
    panel.grid=element_blank(),
    plot.title=element_text(colour = 'red', size=10, face="bold", hjust = 0.5, vjust = 0.5),
    legend.text=element_text(size=9),
    legend.key.size = unit(2, "mm"),
    panel.background = element_rect(fill = "transparent",colour = NA), # or theme_blank()
    plot.background  = element_rect(fill = "transparent",colour = NA),
    panel.grid.minor = element_blank()#, 
    )
texte <- geom_text(
        #mapping = aes(y = (..count.. / sum(..count..))/ c(2, 1) , label = paste0(round(..count.. / sum(..count..) * 100), "%") ),
        mapping = aes(label = paste0(round(..count.. / sum(..count..) * 100), "%") ),
        stat = "count",
        na.rm=TRUE,
)

#Make the graph
    ggplot(graph, aes(x = factor(repondant),fill = factor(RegimeInscription) )) +#Initiation du graphique
    geom_bar(position = "fill") +#Realisation du graphique
    theme_barre + #fond blanc
    coord_flip()+ #barre horizontale
    scale_fill_discrete( name=" ", labels=c("FI"="Fi","FA"="Fa","FC"="Fc") )+
    labs(x=" ", y=" ")+
    scale_y_continuous(breaks=seq(0,1,0.1), labels=percent)+
    ggtitle("Régime d'inscription")+
    texte

我认为问题来自texte值y = ...的注释不是解决方案,因为我有许多具有相同值和不同长度的图形。 图表是根据不同的数据自动生成的,所以我无法指定一些值。

非常感谢

0 个答案:

没有答案