将日期转换为一年中的月份

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

我有一个数据框,其中一列作为时间给出。时间列是 ODE 方程组的模拟结果。我想将时间列转换为一年中的月份。

df <- data.frame(time = c(1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100), 
                 population = c(100, 200, 250, 320, 410, 400, 380, 365, 300, 275, 215))

ggplot(df, aes(x=time, y=population))+
  geom_line()

这会生成一个时间序列图,x 轴上的时间为从 1 到 100 的数字。我希望将这个时间更改为从一月开始的月份。

r dataframe ggplot2 time-series linegraph
2个回答
1
投票

您可以先将时间转换为月数,然后将

scale_x_continuous
month.name
一起使用以获得正确的
breaks
,如下所示:

library(dplyr)
library(ggplot2)
df %>%
  mutate(num_month = round(time/30.417) + 1) %>%
  ggplot(aes(x=num_month, y=population)) + 
  geom_line() +
  scale_x_continuous(breaks = seq_along(month.name), labels = month.name)

创建于 2023-04-24 与 reprex v2.0.2


0
投票

month.abb 给出数字月份的缩写月份标签 1=Jan, 2=Feb...

如果时间以天为单位:

days = c(1,10,20,30,40,50,60,70,80,90,500,600,1000)
months <- round(days/30.417,0)
month.abb[months %% 12]
© www.soinside.com 2019 - 2024. All rights reserved.