将分类分组添加到 R 中连续数据的散点图?

Add categorical grouping to scatter plot of continuous data in R?

抱歉,如果图片 1 is a little basic - layout sent by my project supervisor! I have created a scatterplot of total grey seal abundance (Total) over observation time (Obsv_time), and fitted a gam over the top, as seen in image 2:

plot(Total ~ Obsv_time,
     data = R_Count,
     ylab = "Total",
     xlab = "Observation Time (Days)",
     pch = 20, cex = 1, bty = "l",col="dark grey")
lines(R_Count$Obsv_time, fitted(gam.tot2))

我想以某种方式在图表上显示相应的季节(图片 1)- 来自分类因子变量(4 个级别:育种前、育种、Post-育种、换羽), 对应于 Obsv_time.

我不确定我是否需要绘制辅助轴或只向图表添加标签...以及如何做每一个!谢谢!

Wanted graph layout - indicate season from factor variable Scatterplot with GAM curve

如果您能够使用 ggplot2,您可以向 data-frame 添加(或根据时间计算)另一个因子变量,这将是您的季节。那么这只是一个使用颜色(或任何其他)美学的问题,它会使用这个季节变量。

require(ggplot2)
df <- data.frame(total = c(26, 41, 31, 75, 64, 32, 7, 89),
                 time = c(1, 2, 3, 4, 5, 6, 7, 8))
df$season <- cut(df$time, breaks=c(0, 2, 4, 6, 8),
                 labels=c("winter", "spring", "summer", "autumn"))
ggplot(df, aes(x=time, y=total)) +
  geom_smooth(color="black") +
  geom_point(aes(color=season))

您可以使用基础 R 图形来执行此操作。去掉原图中的 x-axis ,单独添加一个带有季节标签的轴。您可以通过叠加多边形来指示季节。

## Some bogus data
x = sort(runif(50,0,250))
y = 800*(sin(x/40) + x/100 + rnorm(50,0, 0.2)) + 500
FittedY = 800*(sin(x/40) + x/100)+500

plot(x,y, pch= 20, col='lightgray', ylim=c(300,2700), xaxt='n',
    xlab="", ylab='Total')
lines(x, FittedY)
axis(1, at=c(25,95,155,215), tick=FALSE,
    labels=c('PreBreed', 'Repro', 'PostBreed', 'Moulting'))
rect(c(-10,65,125,185), 0, c(65,125,185,260), 3000, 
    col=rainbow(4, alpha=0.05), border=NA)