本文介绍了如何在ggplot2中标记堆叠条形图而不创建汇总数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 下面的代码提供了一个美妙的堆积条形图: cls.grp ser syrclia ggplot(syrclia,aes(cls.grp,fill = ser))+ geom_bar() 我期望geom_text或stat_summary能够标出每个组中负数的百分比并将其放在相应的栏上。我尝试了许多排列,并且无法使其工作。我甚至尝试手动输入百分比,并强制标签在我想要的地方,但它不起作用。它预计有80个标签,我只想给出4个负数或8个标签(如果其中包含正数百分比的标签)。 我真的有吗?制作我的syrclia的聚合数据框并绘制它? 解决方案 geom_bar 默认使用 stat_bin 。因此,您应该使用 stat_bin 来绘制数字,告诉它使用 geom_text 并使用新生成的 .. count .. 作为标签。 cls.grp< - gl(n = 4,k = 20,标签= c(组a,组b,组c,组d)) ser syrclia library(ggplot2) total< - ddply(syrclia,。(cls.grp),function(x)nrow(x))[,2] ggplot(syrclia,aes(cls.grp,fill = ser))+ geom_bar()+ stat_bin(geom =text, aes(label = paste( ..count ../ get(total,envir = .GlobalEnv)* 100, %))) HTH The following code provides a wonderful stacked bar chartcls.grp <- gl(n=4,k=20,labels=c("group a","group b","group c", "group d"))ser <- sample(x=c("neg","pos"),size=80,replace=TRUE, prob=c(30,70))syrclia <- data.frame(cls.grp,ser)ggplot(syrclia, aes(cls.grp, fill=ser))+ geom_bar()I was expecting that with geom_text or stat_summary I would be able to label the percentage who were negative in each group and put it on the corresponding bar. I have tried many permutations and cannot get it to work. I have even tried manually entering the percentages and forcing the labels where I want them but it does not work. It expects 80 labels and I only want to give four that are negative or perhaps 8 (if one includes the labels for the percentage that are positive).Do I really have to make an aggregated data frame of my syrclia and plot that? 解决方案 geom_bar uses stat_bin by default. So you should use stat_bin to plot the numbers, tell it to use geom_text and use the newly produced ..count.. as label. cls.grp <- gl(n=4,k=20,labels=c("group a","group b","group c", "group d")) ser <- sample(x=c("neg","pos"),size=80,replace=TRUE, prob=c(30,70)) syrclia <- data.frame(cls.grp,ser) library(ggplot2) total <- ddply(syrclia, .(cls.grp), function(x) nrow(x))[, 2] ggplot(syrclia, aes(cls.grp, fill=ser))+ geom_bar() + stat_bin(geom = "text", aes(label = paste( ..count../get("total", envir = .GlobalEnv)*100,"%")))HTH 这篇关于如何在ggplot2中标记堆叠条形图而不创建汇总数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-20 22:04