Reputation: 1
I have managed to plot a generalized line, but it is not relevant to my needs. I want to plot line per each treatment and ID and to get the regression values. pic attached here:
I am relatively new with R and couldn't find a proper answer online. Thanks
This is my data:
I want to plot the regression lines for each combination of treatment (0/4/8)* and patient type.
the code that I have written is:
plot(ion_chlorophyll$NA,ion_chlorophyll$CHL)
plot(ion_chlorophyll$NA,ion_chlorophyll$CHL, pch = 1,cex = 1, col = "blue", main = "NA relationship", xlab ="Na", ylab ="CHL")
Upvotes: 0
Views: 1748
Reputation: 651
if you want to get multiple regression lines try using xyplot. Experiment with the iris dataset.
library(lattice)
xyplot(Sepal.Length ~ Sepal.Width, data = iris, pch = 16, type = c("p", "g", "r"), groups = Species, auto.key = TRUE)
If you just have three factors contributing to your 2D plot, then it shouldn't be too much trouble to get the regression lines this way:
model1 <- lm(iris$Sepal.Length[iris$Species == "setosa"] ~ iris$Sepal.Width[iris$Species == "setosa"])
model2 <- lm(iris$Sepal.Length[iris$Species == "versicolor"] ~ iris$Sepal.Width[iris$Species == "versicolor"])
model3 <- lm(iris$Sepal.Length[iris$Species == "virginica"] ~ iris$Sepal.Width[iris$Species == "virginica"])
And do a summary()
of each of the models to get the equations of the regression lines.
I think you should do something like this.
Upvotes: 1
Reputation: 1350
You can do it with ggplot2
if you just want to plot. You can use dplyr
, tidy
and broom
to get the predictions from the model. If df
is your dataframe with columns - treatment, patient_type, Leaf_NA, Total_Chl,
Just plot
library(ggplot2)
p <- df %>% ggplot(aes(Leaf_NA, Total_Chl)) +
facet_grid(treatment ~ patient_type) +
stat_smooth(method='lm')
p
Get model predictions
library(dplyr) #for group_by(), inner_join(), mutate()
library(tidyr) #for nest(), unnest()
library(broom) #for augment()
model <- df %>%
group_by(treatment, patient_type) %>%
do(fit = lm(Total_Chl ~ Leaf_NA, data = .))
df %>%
group_by(treatment, patient_type) %>%
nest() %>%
inner_join(model, .) %>%
mutate(pred = list(augment(fit))) %>%
unnest(pred)
Upvotes: 0