r - 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(" ")
我得到的是这个数字。
我想要得到的是这个图。
解决方案
无法直接使用 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)
推荐阅读
- vba - 尝试通过 Excel-VBA 中的早期/后期绑定创建/设置 Outlook 对象时收到“请求的操作需要提升”
- sql - 用 SQL 中的联接替换子查询
- c++ - 使用 QT 编译:找不到 libGL.so.1
- jenkins - Jenkins Pipeline Downstream Jobs - 在特定阶段继续下一个工作
- spring - 如何使用 Hibernate 3.6.3 在 Spring 3.0.2 中将 Ehcache 迁移到 Infinispan Cache?
- c++ - 具有 std::minmax 和右值的结构化绑定
- asp.net-core - options.UseSqlServer 在 startup.cs 中返回错误
- android - 字符串错误 - 如何修复?
- hazelcast - Hazelcast Jet 滑动窗口测量单位
- php - PHP $_SESSION,试图访问用户表显示没有输出,当会话被终止时,会话保持活动状态