【问题标题】:Plotting a continuous of time data in R在 R 中绘制连续的时间数据
【发布时间】:2016-11-17 16:26:27
【问题描述】:

我正在尝试使用 ggplot 绘制一个晚上的海龟筑巢活动分布,但我想排除上午 8 点到下午 6 点的时间。另外,我需要 x 轴从晚上 7 点开始,到早上 7 点结束。

我的代码是

ggplot(sub.1) + geom_bar(aes(x = sub.1$time)) + scale_x_continuous(expand = c(0, 0), limits = c(0, 23), breaks = seq(0, 23, 1)) + xlab("Hour") +  ylab ("Frequency")

任何帮助将不胜感激。

【问题讨论】:

  • 如果任何人想给您一个具体的答案,您需要提供您正在使用的数据,以便我们可以为您提供与该数据结构相匹配的答案。即请提供dput(sub.1)的结果。也就是说,一般来说,您需要过滤 sub.1 以仅获取夜间数据,并以适当的日期时间格式存储 sub.1$time 以获得您想要的排序。

标签: r plot


【解决方案1】:

试试这个。当我有机会时,我会在那里发布一些cmets。希望对您有所帮助!

# Example Data
SampleHours <- sample(1:23, 3000, replace = TRUE)

# Keep wanted Hours
IncludedHours <- c(19:23, 1:7)
Index <- SampleHours %in% IncludedHours

# Create dataframe
sub.1 <- data.frame(Hour = SampleHours[Index])

# Change the factor levels
sub.1$Hour <- as.factor(sub.1$Hour)

FactorLevels <- c(19:23, 1:7)

levels(sub.1$Hour) <- FactorLevels

# Plot

library(ggplot2)


ggplot(sub.1) + 
  geom_bar(aes(x = sub.1$Hour)) + 
  xlab("Hour") +  
  ylab ("Frequency")

编辑

更改了部分以标识保留哪些时间,而不是排除哪些时间。我认为它更容易关注

【讨论】:

    【解决方案2】:

    我的方法使用dplyr。首先,我生成了一些假数据:

    times = sample(seq(0,23), 10000, replace=T)
    nest = sample(c(0,1), 10000, replace=T)
    data = data.frame(times, nest)
    

    然后,我使用dplyr 来传递结果:

    library(dplyr)
    data %>% filter(times>18 | times<8) %>%
      transform(times=factor(times, levels=c(19:23,0:7))) %>%
      ggplot() + geom_bar(aes(x=times)) +
      xlab("Hour") +
      ylab ("Frequency")
    

    filter 调用选择时间; transform 的作用与 @William 创建订单 19-7 的作用相同。

    【讨论】:

      猜你喜欢
      • 2020-07-03
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      相关资源
      最近更新 更多