首页 > 解决方案 > 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"))

Grp.PieChart

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!

标签: rggplot2

解决方案


您可以通过更改 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 创建


推荐阅读