3

I want to create a dashed line between facet grid ggplot2 plot.

data_people <- data.frame(Group = c("Good", "Medium", "Medium", "Medium", "Medium",  "BAD", "BAD", "BAD", "BAD"),
                          people = c("Jonney", "Eva", "Eilse", "Doe", "Matt", "June", "Som", "Clara","Nick"),
                          number = c(0.04, 0.09, 0.10, 0.13, 0.13, 0.06, 0.05, 0.00, 0.3))
library(ggplot2)
library(ggstance)

ggplot(data = data_people, aes(x = number, y = people, group = Group)) +
  geom_barh(stat = "identity", colour = "black") + 
  scale_x_continuous(breaks = c(-0.20, 0.00, 0.20, 0.40, 0.60, 0.80, 1.00),
                     limits = c(-0.20, 1)) +
  facet_grid(Group~., scales = "free_y", space = "free_y", switch = 'y') +
  xlab(" ") +
  ylab(" ")

What I get is this Figure.

enter image description here

What I want to get is this Figure.

enter image description here

Edo
  • 7,567
  • 2
  • 9
  • 19
Saw Simeon
  • 29
  • 2

2 Answers2

3

There's no way to do this directly with ggplot, instead it's necessary to alter the grob and redraw. Adapting the excellent answer here you can do:

library(ggplot2)
library(grid)
library(gtable)

p <- ggplot(data = data_people, aes(x= number, y = people, group = Group)) +
  geom_bar(stat = "identity", colour = "black") +
  scale_x_continuous(breaks = c(-0.20, 0.00, 0.20, 0.40, 0.60, 0.80, 1.00), limits = c(-0.20, 1)) +
  facet_grid(Group ~ ., scales = "free_y", space = "free_y", switch = 'y') + xlab(" ") +
  ylab(" ") +
  theme()

gt <- ggplotGrob(p)

panels <- subset(gt$layout, grepl("panel", gt$layout$name), t:r)

rows <- unique(panels$b)[-length(unique(panels$b))] + 1

g <- linesGrob(x = unit(c(0, 1), "npc"),
              y = unit(c(.5, .5), "npc"),
              gp = gpar(col = "black", lty = "dotted", lwd = 5) )

gt <- gtable_add_grob(gt, 
                      rep(list(g), length(rows)),
                      r = min(panels$r) - 1, t = rows, l = max(panels$l))

grid.newpage()
grid.draw(gt)

enter image description here

Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56
2

This is the closest I've got so far.

With panel.spacing you adjust the distance between graphs and with panel.border you can define the line around the graphs. If you remove linetype = "dashed" you get just a simple separation line which I think looks better, but it's your call.

library(ggplot2)
# library(ggstance) ## unnecessary

ggplot(data = data_people, aes(x = number, y = people)) +
  geom_col(colour = "black") + 
  scale_x_continuous(n.breaks = 7, limits = c(-0.20, 1)) +
  facet_grid("Group", scales = "free_y", space = "free_y", switch = 'y') +
  labs(x = "", y = "") +
  theme(panel.spacing = unit(0, "lines"),
        panel.border = element_rect(fill = NA, color = "black", linetype = "dashed"))

enter image description here

Edo
  • 7,567
  • 2
  • 9
  • 19