gpt4 book ai didi

r - 使用 scale_x_datetime 和 geom_col 移动 x 轴刻度,使条形不以刻度线为中心

转载 作者:行者123 更新时间:2023-12-03 16:32:33 30 4
gpt4 key购买 nike

我正在以半小时为间隔绘制时间序列数据,使用 geom_col() 显示每个间隔内计数的鸟类数量。 ggplot2 以 x 轴刻度线为中心绘制每个条形图,但我需要每个条形从 开始右 每个刻度线。换句话说,我需要每个条形跨越其相应的半小时间隔的宽度。
我在这些帖子中尝试了建议的解决方案,但没有运气:

  • Bars starting after x-axis tickmark when using scale_x_datetime
  • How to force the x-axis tick marks to appear at the end of bar in heatmap graph?

  • 下面是重现问题的示例代码:
        ``` r
    library(lubridate)
    #>
    #> Attaching package: 'lubridate'
    #> The following objects are masked from 'package:base':
    #>
    #> date, intersect, setdiff, union
    library(ggplot2)
    library(tidyverse)

    df <- data.frame(
    date = c("2019-05-16", "2019-05-16", "2019-05-16", "2019-05-16", "2019-05-16", "2019-05-16", "2019-05-16", "2019-05-16"),
    time = c("16:30:00", "17:00:00", "17:30:00", "18:00:00", "18:30:00", "19:00:00", "19:30:00", "20:00:00"),
    count = c(5, 100, 14, 342, 59, 321, 44, 98),
    stringsAsFactors = FALSE)

    datetime_df <- df %>%
    mutate(time_stamp = paste(date, time) %>% as_datetime())

    plot <- ggplot(datetime_df, aes(x = time_stamp, y = count)) +
    geom_col() +
    scale_x_datetime(breaks = scales::date_breaks("30 mins"), date_labels = "%H:%M",
    limits = c(as_datetime("2019-05-16 16:00:00"),
    as_datetime("2019-05-16 20:30:00"))) +
    scale_y_continuous(expand = c(0,0), breaks = seq(0, 500, by = 50), limits = c(0,500))
    创建于 2020-10-01 由 reprex package (v0.3.0)
    Here is the resulting bar chart
    非常感谢您提供有关如何解决此问题的任何想法!

    最佳答案

    您可以通过在时间上增加 15 分钟来轻松模仿这一点:

    plot <- ggplot(datetime_df, aes(x = time_stamp + minutes(15), y = count)) +
    geom_col() +
    scale_x_datetime(breaks = scales::date_breaks("30 mins"), date_labels = "%H:%M",
    limits = c(as_datetime("2019-05-16 16:00:00"),
    as_datetime("2019-05-16 20:30:00"))) +
    scale_y_continuous(expand = c(0,0), breaks = seq(0, 500, by = 50), limits = c(0,500))
    plot
    enter image description here
    要使刻度线与柱线的起点完全对齐,您需要设置 width geom_col 中的参数以匹配添加的分钟数。经过一些试验和错误后,这似乎有效:
    half_width_in_min = 13
    plot <- ggplot(datetime_df, aes(x = time_stamp + minutes(half_width_in_min ), y = count)) +
    geom_col(width = 60 * 24 * 1.25 * half_width_in_min / 15) +
    scale_x_datetime(breaks = scales::date_breaks("30 mins"), date_labels = "%H:%M",
    limits = c(as_datetime("2019-05-16 16:00:00"),
    as_datetime("2019-05-16 20:30:00"))) +
    scale_y_continuous(expand = c(0,0), breaks = seq(0, 500, by = 50), limits = c(0,500))
    plot
    enter image description here

    关于r - 使用 scale_x_datetime 和 geom_col 移动 x 轴刻度,使条形不以刻度线为中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64148989/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com