geom_col列的左边界与数据锚点对齐

问题描述 投票:0回答:1

我正在尝试使用ggplot2和R绘制带有时间戳的数据。这是我当前工作的一个最小且可重现的示例

library(lubridate)
library(ggplot2)

sample_size <- 100

start_date = as.POSIXct("2020-01-01 00:00")
end_date = as.POSIXct("2020-01-02 00:00")

timestamps <- as.POSIXct(sample(seq(start_date, end_date, by=60), sample_size))
amount <- rpois(sample_size, 5)

df <- data.frame(timestamps=timestamps, amount=amount)

df$hour_group <- floor_date(df$timestamps, unit="1 hour")
ggplot(df, aes(x=hour_group, y=amount)) + geom_col()

说明:首先,创建一个带有列[amount的示例数据框。时间戳在start_dateend_date之间统一选择。我想绘制一天中每个小时的amount变量。因此,将创建另一列hour_group,并用每个时间戳的小时填充。

绘制此数据将产生下图:

enter image description here

这些列看起来不错,但是由于例如第一列表示amount的总和,且时间戳在00:0001:00之间,因此我希望该列完全填充此空间(而不是23:30到[ C0],如当前图所示)。因此,我想使每列的左边界与锚点对齐(在示例00:30中),而不要使列在此点居中。如何实现?

我的方法:我可以想到的一种方法是用锚点移动创建另一列。在此示例中,需要30分钟轮班。

00:00
新图创建预期结果

df$hour_group_shifted <- df$hour_group + 60*30

我仍然想知道是否可能有一种更简单的方法来通过ggplot设置直接实现此目的,而无需额外的列。

r dataframe datetime ggplot2
1个回答
1
投票
您可以使用enter image description here

position_nudge

© www.soinside.com 2019 - 2024. All rights reserved.