使用ggplot2定位堆叠条形图的中心值

编程入门 行业动态 更新时间:2024-10-24 00:28:39
本文介绍了使用ggplot2定位堆叠条形图的中心值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我创建了一个堆叠条形图,并使用两个变量进行分面。我无法将这些值置于中间的条形图中,它可能出现在极端或重叠的位置。期望的图像如下:

I've created a stacked barchart and faceted using two variables. I'm unable to position the values in the barchart in the middle, it either appears at the extremes or overlaps. The expected image is the following:

我粘贴了下面的脚本。任何帮助将不胜感激。

I've pasted the script below. Any help would be appreciated.

library(dplyr) library(reshape2) library(ggplot2) year<-c("2000","2000","2010","2010","2000","2000","2010","2010") area<-c("Rural","Rural","Rural","Rural","Urban","Urban","Urban","Urban") sex<-c("Male","Female","Male","Female","Male","Female","Male","Female") city<-c(58,61,74,65,51,55,81,54)` village<-c(29,30,20,18,42,40,14,29) town<-c(13,9,6,17,7,5,5,17) data<-cbind.data.frame(year,area,sex,city,village,town) dre<-melt(data,id.vars = c("year","area","sex")) dre <- arrange(dre,year,area,sex,variable) %>% mutate(pos = cumsum(value) - (0.5 * value)) a <- ggplot(dre,aes(factor(sex),value,fill=variable)) + geom_bar(stat='identity',position="stack") b <- a + facet_wrap(factor(year)~area) c <- b + geom_text(aes(label=paste0(value,"%"),y=pos), position="stack",size=2,hjust=0.85,color="black") d <- c + coord_flip() + theme_bw() + scale_fill_brewer() print(d)

推荐答案

您不再需要计算位置变量。从ggplot2_2.2.0开始,文本可以通过 position_stack 进行堆叠和居中。

You no longer need to calculate the position variable. Starting in ggplot2_2.2.0, text can be stacked and centered via position_stack.

相关行 geom_text 代码如下。注意我根本不需要使用pos变量来放置文本。

The relevant line of geom_text code is below. Notice I don't need to use the "pos" variable at all for text placement.

geom_text(aes(label=paste0(value,"%")), position = position_stack(vjust = .5), size = 2, color = "black")

剧情和结果图的代码:

The code for the plot and the resulting graph:

ggplot(dre, aes(factor(sex), value, fill = variable)) + geom_col() + facet_wrap(factor(year)~area) + geom_text(aes(label = paste0(value,"%")), position = position_stack(vjust = .5), size = 2, color = "black") + coord_flip() + theme_bw() + scale_fill_brewer()

更多推荐

使用ggplot2定位堆叠条形图的中心值

本文发布于:2023-11-30 03:08:32,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中心   条形图

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!