如何用两线和四个符号制作图形?

时间:2018-11-22 19:05:10

标签: r ggplot2

我想制作一条包含两条线的图形(一条用于水平,另一条用于主因子),但是每个水平在ggplot2上都有两个类别。所以我需要制作一个像这样的图(图像),但是每行有两个符号。请帮助!!!

enter image description here

enter link description here

1 个答案:

答案 0 :(得分:0)

R base中的(潜在)解决方案是这样的:

在数据框中定义数据:

df <- data.frame(Gender = c(rep("m",10), rep("f", 10)),
       Age = sample(10:90, 20, replace = T),
       Fitness_level = sample(1:10, 20, replace = T))

根据年龄级别添加两个不同的点字符:

df$pch <- ifelse(df$Age > 40, 8, 12) # 8 and 12 are point characters

分别针对男性和女性绘制适合年龄的健身水平,并分别添加一条回归线:

# scatter plot:
plot(df$Fitness_level[df$Gender=="m"] ~ df$Age[df$Gender=="m"], pch = df$pch,     col="red", ylim=c(1,10))

# regression line for men:
abline(lm(df$Fitness_level[df$Gender=="m"] ~ df$Age[df$Gender=="m"]), col="red")

# add points for women:
points(df$Fitness_level[df$Gender=="f"] ~ df$Age[df$Gender=="f"], pch = df$pch, col = "blue")

# add regression line:
abline(lm(df$Fitness_level[df$Gender=="f"] ~ df$Age[df$Gender=="f"]), col="blue")

enter image description here