0

I have a stacked bar graph with a single column, and I would like to use ggrepel to put a legend with segments on the side. This is what I have so far:

library(ggplot2)
library(ggrepel)

data <- data.frame(
  id = 1,
  region = factor(c("A", "B", "C")),
  value = c(1, 2, 3)
)

ggplot(data = data, 
       aes(x = id, y = value, fill = region)) +
  geom_bar(position = "stack", stat = "identity", width = 0.1) +
  theme_void() + 
  theme(legend.position = "none",
        legend.margin = margin(c(10, 70, 5, 5))) + 
  geom_text_repel(
    aes(label = region),
    position = position_stack(vjust = 1),
    hjust = 40,
    box.padding = .4
  )

With legend: enter image description here Without legend: enter image description here As you can see, removing the legend has made the plot expand on the full width. My goal is to keep a blank space on the side, where the legend was, so that I can display the labels on the side. How can I do that?

bretauv
  • 7,756
  • 2
  • 20
  • 57
  • Does this answer your question? [ggplot2 plot area margins?](https://stackoverflow.com/questions/10836843/ggplot2-plot-area-margins) – Dubukay Jan 26 '21 at 21:36
  • No, this code doesn't solve my problem (+ I suspect the answer is out of date since the code in it doesn't produce the same output) – bretauv Jan 26 '21 at 21:40
  • 1
    Really? Adding `plot.margin = unit(c(1,5,1,1), "cm")` to your already-existing theme() argument produces a plot that looks almost exactly what you're asking for – Dubukay Jan 26 '21 at 21:44
  • Well actually it creates a blank space on the side, my bad. However, the labels (A, B and C) are not displayed. I think it is because the box of the former legend is overlapping them. They were also not displayed in the first graph I put for the same reason. – bretauv Jan 26 '21 at 21:46
  • 2
    Yeah, ggrepel can be a little finicky sometimes because it wants to decide where the labels go on its own. It looks like you know where the start and end for each label should be - could you use something like geom_segment and geom_text to create your own labels at the specific spots you'd like them to be? – Dubukay Jan 26 '21 at 21:50
  • I'll try but not very comfortable with `ggplot2` and its ecosystem. So I would be quite grateful if you could modify this example (but I'll try on my side anyway). Thanks for your answers so far – bretauv Jan 26 '21 at 21:52
  • Actually, I forgot about that but I have more than 3 regions in my real plot and I think it wouldn't be very convenient to use `geom_segment` and `geom_text`. So if someone has a solution with `ggrepel` too, that would be great – bretauv Jan 26 '21 at 21:59
  • Hi bretauv, I don't think it's clear what you want. Maybe you could create some sample data and code with the 3 regions like your real data and mock up what your expected output would be with mspaint, preview or gimp? – Ian Campbell Jan 28 '21 at 05:04

0 Answers0