我使用ggplot2生成一个多面板图(需要ggplot2包)。十个面板中的每一个代表不同的植物生长形式。我需要在每个面板中绘制一条线,其斜率为0.704。但是,每个面板的截距应该不同,例如“fern”为-7.9,“fern ally”为-7.31等。目前,我使用下面的代码生成斜率和截距均为每个小组都一样:
ggplot(veg, aes(x=ord1, y=log(lai+0.000019))) +
scale_x_discrete(limits=c("1","2","3","4","5","6","7","8","9")) +
scale_y_continuous(limits=c(-12,3)) +
geom_point(shape=1) +
geom_segment(aes(x = 1, xend = 9, y = -8.32 + .704, yend = -8.32 + .704*9),
col = "black", size = 1, lty="longdash", lwd=1) +
facet_wrap( ~ plant_growth_form, ncol=5)
如何在ggplot2中修改此代码,为每个增长表单指定不同的拦截?
使用dput()生成的可重现数据子集可在以下位置找到:How to compute standard errors for predicted data
答案 0 :(得分:1)
首先,创建一个单独的数据框,包含截距和斜率。例如“a”是截距,“b”是斜率。我们将此数据框称为“df3”。
df3 <- data.frame(plant_growth_form = unique(veg[,3]),
a = c(-10,-9,-8,-7,-6,-5,-4,-3,-2,-1), # assigned arbitrarily
b= 0.704)
# plant_growth_form a b
# 1 herb -10 0.704
# 2 moss -9 0.704
# 3 woody climber -8 0.704
# 4 tree sapling -7 0.704
# 5 fern -6 0.704
# 6 herbaceous climber -5 0.704
# 7 undet -4 0.704
# 8 herbaceous shrub -3 0.704
# 9 grass -2 0.704
# 10 woody shrub -1 0.704
ggplot(veg, aes(x=ord1, y=log(lai+0.000019))) +
scale_x_discrete(limits=c("1","2","3","4","5","6","7","8","9")) +
scale_y_continuous(limits=c(-12,3)) +
geom_point(shape=1) +
geom_abline(aes(intercept=a, slope=b), data=df3) +
facet_wrap( ~ plant_growth_form, ncol=5)
# you could separately modify the dataframe of intercepts & slope, or
# adjust directly in the code below for small data (see <--)
df3 <- data.frame(plant_growth_form = unique(veg[,3]),
a = c(-10,-9,-8,-7,-6,-5,-4,-3,-2,-1), # <-- here
b= 0.704) # <-- here
# to add the code of extra segment (see <--), in red.
ggplot(veg, aes(x=ord1, y=log(lai+0.000019))) +
scale_x_discrete(limits=c("1","2","3","4","5","6","7","8","9")) +
scale_y_continuous(limits=c(-12,3)) +
geom_point(shape=1) +
#geom_abline(aes(intercept=a, slope=b), data=df3) +
geom_segment(data = df3, aes(x = 1, xend = 9, y = a + b, yend = a + b*9)) +
geom_segment(aes(x = 1, xend = 9, y = -8.32 + .704, yend = -8.32 + .704*9), # <-- here
col = "red", size = 1, lty="longdash", lwd=1) +
facet_wrap( ~ plant_growth_form, ncol=5)