问题描述
我正在尝试使用ggplot2绘制一些密度图,但分布超出了我的数据范围。具体来说,我试图显示GPS位置在两种栖息地类型中随时间(一天中的小时)的分布。因为我只想显示白天(0500至2100)期间的位置分布,所以我已经滤除了夜间发生的时间。但是,当我绘制数据时,分布在x轴上都超过了5小时和21小时。我感觉到它与ggplot中的“ scale_x_continuous”有关,在其中我将限制指定为(0,24),但这并不能解释为什么分布超出了白天或小时,而在此之前或之后没有数据小时。仅供参考,即使我没有每个小时的数据,我也希望显示整个时间序列。
但是同样,我只有5到21小时之间的数据。 有人可以解释这里发生了什么吗?希望我有道理。谢谢!
示例代码:
locs.19
locs.19 <- subset(locs,hour >= 5 & hour <=21)
> head(locs.19)
ID x y datetime hour shelfhab
2019_01 -122.9979 37.68930 2019-06-07 05:04 5 inner
2019_01 -122.9977 37.68833 2019-06-07 05:06 5 inner
2019_01 -122.9975 37.68737 2019-06-07 05:08 5 inner
2019_01 -122.9974 37.68644 2019-06-07 05:10 5 inner
2019_01 -122.9974 37.68550 2019-06-07 05:12 5 inner
2019_01 -122.9974 37.68457 2019-06-07 05:14 5 inner
> str(locs.19)
'data.frame' : 6531 obs. of 6 variables:
$ ID : chr "2019_01" "2019_01" "2019_01" "2019_01" ...
$ x : num -123 -123 -123 -123 -123 ...
$ y : num 37.7 37.7 37.7 37.7 37.7 ...
$ datetime : chr "2019-06-07 05:04" "2019-06-07 05:06" "2019-06-07 05:08" "2019-06-07 05:10" ...
$ hour : int 5 5 5 5 5 5 5 5 5 5 ...
$ shelfhab : chr "inner" "inner" "inner" "inner" ...
### Plot ###
p19 <- ggplot(locs.19,aes(x = hour))+
geom_density(aes(fill = shelfhab),alpha = 0.4)+
xlab("Time of Day (24 h)")+
theme(legend.position = "right",panel.grid.major = element_blank(),panel.grid.minor = element_blank(),axis.line = element_line(colour = "black"),text = element_text(size = 14,family = "Calibri"))+
scale_x_continuous(breaks=seq(0,24,2),limits = c(0,24),expand = c(0,1))
p19
解决方法
问题是您在scale_x_continuous
中设置了限制。因此,您可以设置估计密度的范围。要获得所需的结果,只需通过coord_cartesian
设置限制。这样,仅在您的数据仍处于0到24小时范围内时,才根据数据估算密度。
使用一些随机示例数据:
set.seed(42)
# Example data
locs.19 <- data.frame(hour = sample(5:21,1000,replace = TRUE),shelfhab = sample(c("inner","outer"),replace = TRUE))
library(ggplot2)
ggplot(locs.19,aes(x = hour))+
geom_density(aes(fill = shelfhab),alpha = 0.4)+
xlab("Time of Day (24 h)")+
theme(legend.position = "right",panel.grid.major = element_blank(),panel.grid.minor = element_blank(),axis.line = element_line(colour = "black"),text = element_text(size = 14))+
scale_x_continuous(breaks=seq(0,24,2),expand = c(0,1)) +
coord_cartesian(xlim = c(0,24))