我试图在一系列日子里绘制动物行为,其中个体动物在散点图中进行颜色编码,并且平滑线显示点上的平均值。我最接近的就是使用这样的格子,其中"站立"是我正在看的具体行为:
xyplot(data=data2,
Standing ~ Day,
type = c("p", "spline"))
这看起来不错,但没有区分点。如果我尝试使用group = Sheep,它也会分割线条。我不知道如何组织一个而不是另一个。
我也尝试过使用ggplot2,但是geo_smooth()似乎没有给我那种我想要的行,下面的代码也不起作用。
means <- tapply(data3$Standing, data3$Day, mean)
ggplot(data3, aes(x = Day, y = Standing)) +
geom_point(aes(colour = Sheep)) +
geom_line(data = data.frame(spline(means)))
我的数据集如下所示:
Sheep Day Block Standing Lying Eating Ruminating Moving Fence Pawing Social Scratching
1 2 -4 0 49 12 36 16 0 0 1 0 0
12 4 -4 0 46 13 32 15 0 2 0 0 0
23 5 -4 0 48 13 32 22 0 0 0 0 0
34 6 -4 0 48 12 36 17 0 0 0 0 0
45 2 -3 0 45 19 39 20 2 0 1 0 0
56 4 -3 0 30 27 35 24 6 4 0 0 0
答案 0 :(得分:1)
在ggplot
结帐stat_smooth
内,我认为这就是你所追求的。
您不需要事先计算means
,因为stat_smooth
应该为您做到这一点。如果您想使用样条线,则有一个spline example here。
在此示例中,它不是非常有用,但根据您的数据集,我可以生成以下图表:
ggplot(data2, aes(x=Day, y=Standing, color=Sheep)) +
geom_point() +
stat_smooth(method=lm)
library(splines)
ggplot(data2, aes(x=Day, y=Standing, color=Sheep)) +
geom_point() +
stat_smooth(method=lm, formula=y~ns(x,3))
答案 1 :(得分:0)
我是否正确理解您想要将个体动物的值仅显示为分数,并且您希望该线总结所有动物的趋势?
如果是这样,那么你需要将绘图分成两个步骤:一个用于生成带有组的着色的散点图,然后用另一个来计算每日平均值并添加一条将它们连接到原始散点图的线。
对于第一步,如果您将分组变量指定为调用颜色的因子,则可以使用基础R中的plot()
按组(绵羊)获取颜色。所以:
with(data2, plot(Standing ~ Day, type = "p", pch=20, col=as.factor(Sheep)))
要按天添加跨群组连接方式的行,请使用tapply()
计算星座常数,spline()
或lowess()
以连接点的方式,{{1将其添加到第一步中创建的现有绘图中。这是使用lines()
的版本:
lowess()
我用这一行来生成播放数据以确认这是有效的:
with(data2, lines(lowess(tapply(Standing, Day, mean)), lwd=2))