gpt4 book ai didi

r - ggplot2 中 facet_grid 的虚线

转载 作者:行者123 更新时间:2023-12-04 03:22:31 25 4
gpt4 key购买 nike

我想在小平面网格 ggplot2 图之间创建一条虚线。

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(" ")

我得到的是这张图。

enter image description here

我要得到的是这张图。

enter image description here

最佳答案

无法直接使用 ggplot 执行此操作,而必须更改 grob 并重绘。改编优秀答案here你可以这样做:

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

关于r - ggplot2 中 facet_grid 的虚线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68223747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com