如何根据每个方面的因素创建两条不同的回归线? R,ggplot2
How to create two different regression line based on factor for each facet? R, ggplot2
我正在尝试根据 exercise = 0 或 exercise = 1 为每个方面(按性别)创建两条不同的线。第一个代码没有 facet_wrap 并且基于性别的两行是不同的。第二个代码是 facet_wrap 并且这两行似乎是同一行。我怎样才能更改代码,使两行在每个方面都不同?
ggplot(cdc, aes(weight,wtdesire, color = exercise, group =
interaction(gender,exercise))) + geom_point(alpha = 1/5) +
geom_smooth(method = lm, aes(linetype=exercise))
产生:facet
但是,当我添加 facet_wrap 时,每个方面的两条线似乎是相同的。
ggplot(cdc, aes(weight,wtdesire, color = exercise, group =
interaction(gender,exercise))) + geom_point(alpha = 1/5) +
geom_smooth(method = lm, aes(linetype=exercise)) + facet_wrap(~gender)
产生:second
@LoBu 解法正确。这是一个使用 mtcars 数据的示例:
ggplot(mtcars, aes(hp, mpg, group=interaction(vs, am))) +
geom_point(alpha = 0.2) +
geom_smooth(method = lm, aes(linetype=as.factor(vs)))
ggplot(mtcars, aes(hp, mpg, group=vs)) +
geom_point(alpha = 0.5) +
geom_smooth(method = lm, aes(linetype=as.factor(vs))) +
facet_wrap(~am)
我正在尝试根据 exercise = 0 或 exercise = 1 为每个方面(按性别)创建两条不同的线。第一个代码没有 facet_wrap 并且基于性别的两行是不同的。第二个代码是 facet_wrap 并且这两行似乎是同一行。我怎样才能更改代码,使两行在每个方面都不同?
ggplot(cdc, aes(weight,wtdesire, color = exercise, group =
interaction(gender,exercise))) + geom_point(alpha = 1/5) +
geom_smooth(method = lm, aes(linetype=exercise))
产生:facet
但是,当我添加 facet_wrap 时,每个方面的两条线似乎是相同的。
ggplot(cdc, aes(weight,wtdesire, color = exercise, group =
interaction(gender,exercise))) + geom_point(alpha = 1/5) +
geom_smooth(method = lm, aes(linetype=exercise)) + facet_wrap(~gender)
产生:second
@LoBu 解法正确。这是一个使用 mtcars 数据的示例:
ggplot(mtcars, aes(hp, mpg, group=interaction(vs, am))) +
geom_point(alpha = 0.2) +
geom_smooth(method = lm, aes(linetype=as.factor(vs)))
ggplot(mtcars, aes(hp, mpg, group=vs)) +
geom_point(alpha = 0.5) +
geom_smooth(method = lm, aes(linetype=as.factor(vs))) +
facet_wrap(~am)