-1

I have a data frame with one of the columns given as time. The time column is as a result of simulations from ODE system of equations. I want to convert the time column to months of the year.

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()

This produces a time series plot with time in the x-axis as numbers from 1 to 100. I want this time to be changed to months starting from January.

Quinten
  • 35,235
  • 5
  • 20
  • 53
Joseph
  • 1
  • 1
  • You should clarify: what unit is `time` in? Is that months?, such that t=1 is January and t=10 is October of the same year, and t=20 is August of the subsequent year, etc? – langtang Apr 24 '23 at 17:16
  • @langtang you skipped over the Differential Equation part – stefan_aus_hannover Apr 24 '23 at 17:18
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Apr 24 '23 at 20:03
  • I am sorry for the confusion in the question. Time is in days and population is just numbers. And so the task is how do I convert time in days to months. I hope this clarifies it. Thank you. – Joseph Apr 25 '23 at 08:09

2 Answers2

1

You could first convert your time to month number and use scale_x_continuous with month.name to get the right breaks like this:

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)

Created on 2023-04-24 with reprex v2.0.2

Quinten
  • 35,235
  • 5
  • 20
  • 53
0

month.abb give the abbreviated month label from a numerical month 1=Jan, 2=Feb...

If time is in days:

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]
Yano
  • 598
  • 5
  • 12