Search code examples
rggplot2ggrepel

Changing the position of the label in a donut chart


I am trying to move the position of the label in a donut chart to be at the right side of the chart but I am not able to do it. I am using ggplot and ggrepel to make the graph.

library(ggplot2)
library(ggrepel)

expenditurePie = data.frame(
  value = c(98,2),
  area = c("A","B"),
  label = c("","This is a label"))

ggplot(expenditurePie, aes(y=value, fill = area, label = label)) +
  geom_bar(aes(x = 4), stat = "identity", show.legend = F) +
  geom_text_repel(size = 5, x= 4, point.padding = unit(1.8, "lines"), direction = "x") +
  xlim(0.5, 4.5) +
  annotate(geom = "text", x=0.5, y=0, label = "24 444", size = 16, color = "grey") +
  scale_fill_manual(values = c(A = "grey", B = "black")) +
  coord_polar(theta = "y", start = 1) +
  theme_void() +
  theme(legend.position = 'none')

The image below is the result of the code above: enter image description here

But the image below shows what I need: enter image description here

How can I do it? Thanks.


Solution

  • Maybe this is an option for you. Instead of relying on the magic of ggrepel my approach sets the label manually (still using ggrepel but with force set to 0) and while drawing the segment using geom_segement. Try this:

    library(ggplot2)
    library(ggrepel)
    
    expenditurePie = data.frame(
      value = c(98,2),
      area = c("A","B"),
      label = c("","This is a label"))
    
    ggplot(expenditurePie, aes(y = value, fill = area, label = label)) +
      geom_bar(aes(x = 4), stat = "identity", show.legend = F) +
      geom_text_repel(size = 5, x = 7, point.padding = unit(1.8, "lines"), direction = "x", force = 0, seed = 42) +
      geom_segment(aes(x = 4.6, xend = 5.5, y = 1, yend = 1)) +
      xlim(0.5, 5.5) +
      annotate(geom = "text", x=0.5, y=0, label = "24 444", size = 20, color = "grey") +
      scale_fill_manual(values = c(A = "grey", B = "black")) +
      coord_polar(theta = "y", start = 1) +
      theme_void() +
      theme(legend.position = 'none')
    

    Created on 2020-05-25 by the reprex package (v0.3.0)