【问题标题】:Density plot exceeds x-axis interval密度图超过 x 轴间隔
【发布时间】:2021-01-26 11:10:23
【问题描述】:

我正在尝试使用 ggplot2 制作一些密度图,但分布超出了我的数据范围。具体来说,我试图展示 GPS 位置随时间(一天中的几个小时)在 2 种栖息地类型中的分布。由于我只对显示白天(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

【问题讨论】:

    标签: r ggplot2 density-plot


    【解决方案1】:

    问题是您在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"), 1000, 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))
    

    【讨论】:

    • 工作就像一个魅力。非常感谢!!
    猜你喜欢
    • 2021-06-16
    • 2017-09-24
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多