gpt4 book ai didi

r - 如何减少日期的ggplot中x轴的超前/滞后空间

转载 作者:行者123 更新时间:2023-12-04 11:07:16 25 4
gpt4 key购买 nike

我使用 scale_x_continuous 缩小 ggplot 上的超前/滞后空间。它适用于数字 x 轴对象。然而,我对约会没有任何兴趣。

我的例子:

library(lubridate)  
library(tidyverse)

# this works
ggplot(cars, aes(x = speed, y = dist)) +
geom_line() +
scale_x_continuous(expand = c(0, 0))


# this does not work
cars %>%
mutate(date = seq(dmy("01/01/2019"), dmy("01/01/2019") + ddays(nrow(cars) - 1), "day")) %>%
ggplot(aes(x = date, y = dist)) +
geom_line() +
scale_x_continuous(expand = c(0, 0))

有什么想法吗?

最佳答案

在 X 轴上,您正在处理 date 类型的数据,而不是 continuous 数据。

您可以使用以下代码

cars %>% 
mutate(date = seq(dmy("01/01/2019"), dmy("01/01/2019") + ddays(nrow(cars) - 1), "day")) %>%
ggplot(aes(x = date, y = dist)) +
geom_line() +
scale_x_date(expand = c(0, 0))

产生以下情节

enter image description here

关于r - 如何减少日期的ggplot中x轴的超前/滞后空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56661545/

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