首页 文章

使用带连续变量的geom_smooth时ggplot2的线型和引导选项

提问于
浏览
0

我正在使用ggplot2和geom_smooth函数来从lm模型中生成预测线 . 我在ggplot代码中使用连续的y和x函数 .

我试图为图中的每一行创建一个不同的线型(这是变量“位置”,范围从-1,0或1),我想在指南中列出每个位置(其中-1 =位置A,0 =位置B,1 =位置C) . 我的代码的可复制摘录如下:

#test scores that range from 1 to 7
score <- c(6, 3, 5, 6, 7, 2, 4, 6, 3, 5, 4, 3, 3, 1, 3, 3, 3, 5, 2, 3, 2, 2, 7, 3, 7,     5, 4, 1, 3, 2, 7, 6, 6, 3, 6)
#location of the school
location <- c(1,  0,  0,  0,  1,  1,  1, -1,  1, -1,  0, -1,  0,  1,  0,  0,  0, -1,     0, -1,  0, -1,  0,  0,  0,  0,  0, -1,  0, -1,  0,  0,  0,  1,  0)

IQ <- c(0.7171425604,    0.7056850461,    1.3929736220,    0.0633936624,   -0.6872828336,   -1.3665840767,    1.4368569944, 0.7297599487,   -0.5735047485,   -0.6752912747,   -0.6213572428,   -0.6110533924,   -0.7090921238,    0.0501744806, 1.3916802944,   -0.0055243194,    1.3619753292,    1.4406369365,    0.6529601586,    0.0538097896,    1.3821853866, 1.3870600993,    0.0040551996,    0.6600558495,    1.3550162100,    1.3081187951,   -1.7541949601,    1.3768167017, -0.6232446826,   -1.2793074919,    0.0560708725,   -0.5993356051,   -0.5857733192,   -0.6005459705,   -0.6659873442)

df <- data.frame(score, location, IQ)

p1 <- ggplot(data=df,aes(y=score,x=IQ,shape=factor(location))) + 
geom_smooth(method = "lm", se=F) + scale_y_continuous("Test Score",limits=c(1,7)) +
scale_x_continuous("IQ level", limits=c(-2.45, 1.45)) + 
theme_bw() +
theme(axis.text.x=element_text(size=rel(1.2), color = 'black'),
    axis.title.x=element_text(size=rel(1.3)),
    axis.title.y=element_text(size=rel(1.3)),
    axis.text.y=element_text(size=rel(1.2), color = 'black'),
    panel.grid.minor=element_blank(),
    panel.grid.major.x=element_blank(),
    panel.grid.major.y=element_blank(),
    axis.ticks.y = element_blank(), 
    panel.border = element_blank(),
    plot.title = element_text(size = rel(1.4))) 

print(p1)

每当我尝试添加线型或手动线型时,我一直都会遇到有关如何使用连续变量(仅离散)映射线型的错误 . 有什么方法可以解决这个问题,还是应该使用不同的功能?也许事先为位置(学校1,学校2和学校3?)的值创建标签?或者我应该使用替代线型?我无法在线或在Wickham的书中找到解决方案 . 谢谢!

1 回答

  • 1

    您收到此错误消息是因为 location 是连续变量(数字变量在ggplot中被视为连续变量)而对于 linetype= ,只能使用离散变量 . 将它用于 linetype=location 转换为因子 . 要更改图例中的标签,请使用s cale_linetype() 并提供参数 labels= .

    ggplot(data=df,aes(y=score,x=IQ,linetype=factor(location))) + 
      geom_smooth(method = "lm", se=F) + scale_y_continuous("Test Score",limits=c(1,7)) +
      scale_x_continuous("IQ level", limits=c(-2.45, 1.45)) +
      scale_linetype(labels=c("Location A","Location B","Location C"))
    

相关问题