为 facet_grid 中的级别添加唯一的水平线
Add unique horizontal line for levels in facet_grid
我想在一组分面网格箱线图的每一行中添加一条唯一的水平线。
x<-c("species_X","species_X","species_X", "species_Y","species_Y",
"species_Y", "species_Z", "species_Z", "species_Z")
y<- c(1,2,3)
df<- data.frame(species= rep(x, 3),
effort= rep(y, 9),
value = rnorm(27, 3, 2))
ggplot(df, aes(x=value))+
geom_boxplot()+
facet_grid(species ~ effort, scales = "free_y")+
coord_flip()+
ylab("")
我想为每行添加以下值的行:
add_lines<- c(4, 3, 4.7)
所以4对应species_X,3对应species_Y,4.7对应species_Z。我已经能够向所有箱线图添加线,但只能以所有线具有相同值的方式添加,或者所有三条线都显示在每个箱线图上,如下所示:
ggplot(df, aes(x=value))+
geom_boxplot()+
facet_grid(species ~ effort, scales = "free_y")+
coord_flip()+
ylab("")+
geom_vline(xintercept = add_lines)
如有任何帮助,我们将不胜感激。
只需在 x 截距中包含分面变量。做一个小数据框是最简单的
add_lines <- data.frame(y = rep(c(4, 3, 4.7), each = 3),
species = x,
effort = rep(y, 3))
ggplot(df, aes(value)) +
geom_boxplot() +
facet_grid(species ~ effort, scales = "free_y") +
coord_flip() +
ylab("") +
geom_vline(aes(xintercept = y), data = add_lines, color = "red")
coord_flip
扰乱了线条的方向,但更改为 geom_vline
会修复它。
将物种设置为 unique
并保护数据框中的行数。
library(tidyverse)
# data for lines
add_lines = data.frame(species = unique(df$species),
hline = c(4,3,4.7)
)
p <- ggplot(df, aes(x=value))+
geom_boxplot()+
facet_grid(species ~ effort, scales = "free_y")+
coord_flip()+
ylab("")
p +
geom_vline(data = add_lines,
aes(xintercept = hline), color = "green")
我想在一组分面网格箱线图的每一行中添加一条唯一的水平线。
x<-c("species_X","species_X","species_X", "species_Y","species_Y",
"species_Y", "species_Z", "species_Z", "species_Z")
y<- c(1,2,3)
df<- data.frame(species= rep(x, 3),
effort= rep(y, 9),
value = rnorm(27, 3, 2))
ggplot(df, aes(x=value))+
geom_boxplot()+
facet_grid(species ~ effort, scales = "free_y")+
coord_flip()+
ylab("")
我想为每行添加以下值的行:
add_lines<- c(4, 3, 4.7)
所以4对应species_X,3对应species_Y,4.7对应species_Z。我已经能够向所有箱线图添加线,但只能以所有线具有相同值的方式添加,或者所有三条线都显示在每个箱线图上,如下所示:
ggplot(df, aes(x=value))+
geom_boxplot()+
facet_grid(species ~ effort, scales = "free_y")+
coord_flip()+
ylab("")+
geom_vline(xintercept = add_lines)
如有任何帮助,我们将不胜感激。
只需在 x 截距中包含分面变量。做一个小数据框是最简单的
add_lines <- data.frame(y = rep(c(4, 3, 4.7), each = 3),
species = x,
effort = rep(y, 3))
ggplot(df, aes(value)) +
geom_boxplot() +
facet_grid(species ~ effort, scales = "free_y") +
coord_flip() +
ylab("") +
geom_vline(aes(xintercept = y), data = add_lines, color = "red")
coord_flip
扰乱了线条的方向,但更改为geom_vline
会修复它。将物种设置为
unique
并保护数据框中的行数。
library(tidyverse)
# data for lines
add_lines = data.frame(species = unique(df$species),
hline = c(4,3,4.7)
)
p <- ggplot(df, aes(x=value))+
geom_boxplot()+
facet_grid(species ~ effort, scales = "free_y")+
coord_flip()+
ylab("")
p +
geom_vline(data = add_lines,
aes(xintercept = hline), color = "green")