简体   繁体   中英

Unable to Plot Multiple lm Lines on ggplot in R

I am trying to plot multiple lm lines on a ggplot, but not even one seems to show up on it. I can't make heads or tails of it. I wanted to plot each lm line - representing 'medium', 'high' and 'low' from a categorical field - but not even a singular one is showing up. Can someone guide me as to what I'm doing wrong?

I have already tried using the geom_smooth() and stat_smooth() functions along with varying definitions of each function's method formulas, such as (method = "lm", formula = variable ~ value) but to no avail.

data1B = data.frame(B_1=c(561.5806, 585.9286, 597.4839), B_2=c(780.5758, 
800.8750, 754.8788), B_3=c(767.4545, 771.6250, 778.6471), B_4=c(868.3448, 
1062.4000, 1184.4242), data.SWASH_group=c("low", "medium", "low"))

library(dplyr)
library(reshape2)

library(ggplot2)

d <- melt(data1B, id.vars="data.SWASH_group")
View(d)

# Everything on the same plot
ggplot(d, aes(variable, value, col=variable)) + geom_smooth(method="lm")+
geom_point(aes(col=data.SWASH_group, size=2)) +  
stat_smooth()

The result I am achieving is the following: 在此处输入图片说明

The result I want to achieve looks something like this:

在此处输入图片说明

Note: The output is more dense because it has more data points to plot, instead of the sparse data points I provided in my example for recreation purposes. Also, each lm line on the plot is representing one type of the categorical variable, such as 'high' and 'low' here more specifcally.

make sure the variables (low and medium) are recognized as groups

ggplot(d, aes(variable, value, col=variable, group=as.factor(variable)) +
geom_point(aes(col=data.SWASH_group, size=2)) +  
stat_smooth()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM