对于如何将标准化主轴(SMA)回归线绘制成多面ggplot,我将不胜感激。我使用了以下代码:
smaReg = sma(Y ~ X * Type, data = ExampleData)
summary(smaReg)
smaSummary <- data.frame(Type = 1:6,coef(smaReg))
ModFit <- ggplot(ExampleData, aes(y = Y, x = X, color = Level)) +
geom_point() +
theme_bw() +
theme_classic() +
facet_wrap(~ Type, nrow = 2, ncol = 3) +
theme(strip.background = element_blank(), strip.text = element_text(face = 'bold', size = 12)) +
annotate("segment", x = -Inf, xend = Inf, y = -Inf, yend = -Inf, color = 'black', size = 1) +
annotate("segment", x = -Inf, xend = -Inf, y = -Inf, yend = Inf, color = 'black', size = 1) +
scale_x_continuous(breaks = seq(from = 0, to = 60, by = 20)) +
scale_y_continuous(breaks = seq(from = 0, to = 120, by = 20)) +
geom_abline(data = smaSummary, aes(intercept = elevation, slope = slope)) +
labs(x = expression(paste("Predicted (",mu,"mol m"^{-2},"s"^{-1},")")), y = expression(paste("Observed (",mu,"mol m"^{-2},"s"^{-1},")"))) +
ModFit
此代码还有两个尚待解决的问题,但我的初学者编码技能尚不足以成功解决它们:
我使用annotate()和scale_x_continuous在所有多面图中绘制了相同的轴和比例,但是,此解决方案无法绘制X轴刻度线,因此我没有找到一种方法来完成此任务我进行更改时出了错。
运行此绘图代码时,出现以下错误消息:
wrap_dims(n,params $ nrow,params $ ncol)中的错误: nrow * ncol> = n不为真
在尝试解决该错误的不同方式时,我注意到如果将labs()层更改为如下所示的非常简化的版本:
labs(x = expression(X), y = expression(Y), color = "Level") +
此更改将生成多面图,但每个图上均具有所有SMA回归。我不知道为什么更改labs()层可以生成图!我对如何仅为每个图绘制对应的SMA reg线(同时还添加我需要的详细轴标签而没有其他问题)的想法(和Google搜索)用光了。
Faceted plot with simplified labels and all SMA reg lines on each plot
在此先感谢您提供有关如何解决这两个剩余问题的建议!
答案 0 :(得分:0)
(已更新:添加了希腊数学符号)
让我们解决标签,在您的示例中这非常棘手。我将虹膜数据集用作示例,但使用的是轴标题。
关键是使用bquote()
来获取数学,动态变量和其他所有内容。
library(tidyverse)
mu_val <- 5.1
bq_x <- bquote("Predicted (" ~ mu ~ "=" ~ .(mu_val) ~ " mol " ~ m^-2 ~ s^-1 ~ ")")
bq_y <- bquote("Observed (" ~ mu ~ "=" ~ .(mu_val) ~ "mol m" ~ m^-2 ~ s^-1 ~ ")")
iris %>%
ggplot(aes(Sepal.Length, Petal.Length)) +
geom_point() +
labs(title = "test", x = bq_x, y = bq_y)
由reprex package(v0.3.0)于2019-11-19创建
@ravic_感谢您的建议,我现在可以使用以下修改后的代码生成带有正确标签的多面图:
我更新了我的ggplot代码:
bq_x <- bquote("Predicted (" ~mu~"mol" ~ m^-2 ~ s^-1 ~ ")")
bq_y <- bquote("Observed (" ~mu~"mol" ~ m^-2 ~ s^-1 ~ ")")
# 1a. Plots by PFTs
ModFit <- ggplot(ExampleData, aes(y = Y, x = X, color = Level)) +
geom_point() +
theme_bw() +
theme_classic() +
facet_wrap(~ Type, nrow = 2, ncol = 3) +
# customise facet labels
theme(strip.background = element_blank(), strip.text = element_text(face = 'bold', size = 12)) +
annotate("segment", x = -Inf, xend = Inf, y = -Inf, yend = -Inf, color = 'black', size = 1) +
annotate("segment", x = -Inf, xend = -Inf, y = -Inf, yend = Inf, color = 'black', size = 1) +
scale_x_continuous(breaks = seq(from = 0, to = 60, by = 20)) +
scale_y_continuous(breaks = seq(from = 0, to = 120, by = 20)) +
labs(x = bq_x, y = bq_y) +
geom_abline(data = smaSummary, aes(intercept = elevation, slope = slope))
现在剩下的两个问题是: 1.在所有多面图上添加带有刻度线的Y和X轴线 2.在每个图中添加相应的SMA reg单线
再次感谢您对@ravic_的所有帮助!