我正在尝试创建一个图表,显示随着时间的推移物种的丰富性。我希望最终的图形看起来像是使用geom_density制作的,每个物种都有平滑的曲线。例如,此站点上的图1 (Figure 1)。然而,我不能操纵R来使用我的y值(丰度)而不是密度计数。我确实设法使用了geom_area,但这并不是我想要的输出。有人知道如何让geom_density接受y值吗?或者,用平滑的曲线绘制物种丰富度?
示例:
data.set <- data.frame(
Time = c(rep(1, 4),rep(2, 4), rep(3, 4), rep(4, 4)),
Type = rep(c('a', 'b', 'c', 'd'), 4),
Value = rpois(16, 10)
)其中,值是物种丰度,时间是记录每个丰度的时间点,类型表示四个不同的物种。
ggplot(data.set, aes(Time, Value)) + geom_area(aes(fill = Type))一旦绘制出来,它就会变得非常“结实”。我更喜欢使用像geom_density这样的东西来制作平滑的曲线,然后使用alpha来使它们透明。
任何帮助都将不胜感激!
发布于 2016-04-14 08:45:18
你可以使用spline()进行插值(根据2010年的this答案)
library(ggplot2)
library(data.table) #for rbindlist
# break data.frame into chunks by type
type_chunks <- split(data.set, data.set$Type)
# apply spline function to each chunk
spline_chunks <- lapply(seq_along(type_chunks), function(i) {
x <- type_chunks[[i]]
data.frame(Type=names(type_chunks)[i],
spline(x$Time, x$Value, n=50)) # choose a value for n
})
# crush chunks back to one data.frame
spline_df <- rbindlist(spline_chunks)
# original plot
ggplot(data.set, aes(Time, Value)) + geom_line(aes(color = Type), size=2)
# plot smoothed version
ggplot(spline_df, aes(x, y)) + geom_line(aes(color = Type), size=2)原图

平滑版本

注意:我将这些作为线状图,而不是面积图,因为这与您链接的帖子相匹配,并且面积图将系列显示为堆叠而不是独立的。
发布于 2016-04-15 22:56:44
有趣的是,在这种情况下,如果数据集未汇总,则可以使用stat_density。
在基于Value添加行的Value中,根据汇总的计数来扩展像这样的简单数据集非常容易。请参见options here。
# Make expanded dataset
d2 = data.set[rep(row.names(data.set), data.set$Value), 1:2]
head(d2)
Time Type
1 1 a
1.1 1 a
1.2 1 a
1.3 1 a
1.4 1 a
1.5 1 a然后,您可以为y美学使用..count..制作所需的绘图。可以绘制密度图,也可以使用stat = "density"绘制线形图。下面是后者的一个示例。
ggplot(d2, aes(Time, y = ..count.., color = Type)) +
geom_line(size = 1, stat = "density")

https://stackoverflow.com/questions/36611690
复制相似问题