首页 > 解决方案 > ggplot2中facet_grid的虚线

问题描述

我想在 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(" ")

我得到的是这个数字。

在此处输入图像描述

我想要得到的是这个图。

在此处输入图像描述

标签: rggplot2

解决方案


无法直接使用 ggplot 执行此操作,而是需要更改 grob 并重绘。在此处调整出色的答案,您可以执行以下操作:

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)

在此处输入图像描述


推荐阅读