第一个计时器到了!我有一个关于不同土壤深度铁和铬浓度的数据框架。我想绘制所有的数据,但是我想创建一个线性模型,在同一个图中只有3个不同深度的数据。变量'depth‘是一个因素。另外两个是数字的。
我尝试使用subset
,但是--显然--我只能创建一个只有一个子集的lm
。filter
和[]
也不能工作。
当我尝试这样做的时候:
seq15 %>% filter(depth == "0-3", depth == "3-5", depth == "5-10") %>%
ggplot(aes(Fe, Cr, color=depth)) + geom_point()
这张图一片空白。
当我尝试这样做的时候:
seq15 %>% ggplot(aes(Fe, Cr, color=depth)) +
geom_point() + geom_smooth(data = subset(seq15, depth == "0-3" & depth == "3-5" & depth == "5-10"), method = lm, se = FALSE)
所有的数据都被绘制出来了,但是没有lm
。
头部如下:
head(as_tibble(seq15))
# A tibble: 6 x 9
points depth Cr Cu Fe Mn Ni Pb Zn
<fct> <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 CAPA 0-3 50.8 17.7 48291 412. 14.2 18.3 32.8
2 P3 0-3 0-3 82.3 26.3 59696 1152 34.8 26 74.5
3 P3 3-5 3-5 19.5 1.81 21944 201. 4.61 2.66 12.1
4 P3 5-10 5-10 19.2 2.09 28234 213. 4.43 3.05 14.3
5 P3 20-25 20-25 14.1 1.53 8751 185. 4.82 1.86 7.66
6 P4 Borda Lagoa ~ 0-3 60.4 18.7 42646 336 25 17 65
发布于 2019-09-26 22:53:29
我的解决方案包括对数据进行子集划分,使用这个子集拟合线性模型,添加拟合值,然后绘制结果。
##Subset the data
data_subset <- filter(seq15, depth %in% c("0-3", "3-5","5-10"))
lm_model <- lm(Cr~Fe, data = data_subset)
##Add the fitted values
data_subset <- data_subset %>%
mutate(fitted_values = fitted(lm_model))
##Plot the data and the fitted values for the linear model
seq15 %>% ggplot(aes(Fe, Cr, color=depth)) +
geom_point() +
geom_line(aes(x = Fe, y = fitted_values),
data = data_subset, inherit.aes = FALSE)
发布于 2019-09-26 22:54:08
在这种情况下,这可能是一个过滤器问题,如果您与dput()
共享数据,我可以为您提供一个示例:
library(dplyr)
#>
#> Attachement du package : 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(ggplot2)
iris %>%
filter(Species != "setos" & Species != "seto") %>%
ggplot(data = ., aes(Sepal.Length, y = Sepal.Width, colour = Species)) +
geom_point() +
geom_smooth(method = "lm", formula = "y ~ x")
发布于 2019-09-26 22:50:41
据我所知,您希望为每个单独的组创建一个lm。
有一个类似的问题,也许答案会对你有所帮助。
https://stackoverflow.com/a/17195512/6625053
祝你一切顺利,迈克尔
再次问候,请尝试此代码:
seq15 %>%
filter(depth == "0-3" | depth == "3-5" | depth == "5-10") %>%
ggplot(aes(x = Fe, y = Cr)) +
geom_point(mapping = aes(color = depth)) +
geom_smooth(method = lm, se = FALSE)
问题是,如果在过滤条件之间使用“filter”命令中的逗号,则不会获得任何数据。|是逻辑上的“OR”,否则您将使用“AND”条件进行筛选。
https://stackoverflow.com/questions/58119101
复制相似问题