r - How can I move geom_text labels further out on a ggplot pie chart?
问题描述
I have some survey data for six groups of respondents (res). I've added a column for the colour I want to assign each group in my chart, though that's probably redundant. I've made a pie chart which shows the number of respondents in each group:
Grp.PieChart <- ggplot(data = count(res, Grp, GrpColour), aes(x = "", y = n, fill = GrpColour)) +
geom_bar(stat = "identity") +
coord_polar(theta = "y") +
theme_void() +
geom_text(aes(label = n),
size = 8,
colour = "#161844",
family = "Raleway",
position = position_stack(vjust = 0.5)) +
ggtitle("Groups of Respondents") +
theme(
legend.title = element_blank(),
legend.text = element_text(colour = "#161844", size = 12, family = "Raleway"),
plot.title = element_text(colour = "#161844", size = 24, family = "Raleway", face = "bold")) +
scale_fill_manual(values = c("#21409A", "#6C217E", "#30BAED", "#39B44A", "#FFDA00", "#F47920"),
breaks = c("#21409A", "#6C217E", "#30BAED", "#39B44A", "#FFDA00", "#F47920"),
labels = c("Group A", "Group B", "Group C", "Group D", "Group E", "Group F"))
I'm pretty happy with the chart, I just want to move the numbers a bit further away from the centre. At the moment they're about halfway between the centre and the edge, I want them to be about 75% of the way from the centre and 25% of the way from the edge.
I've tried various configurations of position_stack, position_dodge, nudge_x, nudge_y, can't seem to make it work. I'm pretty new to R as well...
My data looks like this (209 rows in total):
Grp GrpColour
Group F #F47920
Group B #6C217E
Group E #FFDA00
etc
Help would be much appreciated!
解决方案
您可以通过更改 x 值来实现geom_text
library(tidyverse)
mydat <- data.frame(n = c(4,27,12,30,85,51), group = LETTERS[1:6])%>% mutate(nperc = n*100/sum(n))
ggplot(data = mydat, aes(x ='', y= nperc, fill = group)) +
geom_col() +
geom_text(aes(x = 1.2,label = n), position = position_stack(vjust = 0.5)) +
coord_polar(theta = 'y') +
scale_fill_manual(values = c("#21409A", "#6C217E", "#30BAED", "#39B44A", "#FFDA00", "#F47920"))
由reprex 包(v0.3.0)于 2020-03-24 创建
推荐阅读
- azure - Azure 1GB 共享账户,磁盘空间不足
- vue.js - vuex-persistedstate -- js-cookie 版本如何实现?
- angular - Angular @Input 以编程方式为 3rd 方控件设置
- .net - Azure DevOps 将 IIS 部署到 Windows 服务器密码限制?
- google-apps-script - 增加列中的所有单元格值
- python - Open Street MAP 无法检索所有信息
- qt - QML DropArea 外部文件失败
- sql - 你能数出两个表格中两列的不同单元格吗?
- javascript - 如何获取传入的状态响应?
- javascript - 如果 Date_1 > Date_2 则运行脚本