0

I have been working on a plot in R using ggplot and plotting dates on the x axis. I have noticed that R does not recognize them as dates, and so the order on the x axis is wrong. I have tried many different things such as using as.Date(), manually editing levels and ordering the x axis, but nothing has worked. Here's my code:

library(dplyr)
library(ggplot2)
library(hrbrthemes)

calories_data = read.csv('dailyCalories_clean.csv',header = TRUE, sep=",")

ggplot(calories_data, aes(x= ActivityDay, y=Calories, group=Id, color = Id))+
  geom_line()

Here's the plot

I appreciate any help, I'm new at this and have been researching for hours with no success. Thank you!

Maira L
  • 3
  • 1
  • Welcome to SO! It would be easier to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. If you want to post your data type `dput(NAME_OF_DATASET)` into the console and copy the output starting with `structure(....` into your post. If your dataset has a lot of observations you could do e.g. `dput(head(NAME_OF_DATASET, 10))` for the first ten rows of data. – stefan Jun 23 '22 at 15:06

1 Answers1

0

One option to fix your issue would be to convert your dates to proper dates to fix the order and use the date_labels argument of scale_x_date to format your dates. To convert to dates you have to add a fake year to your ActivityDay, e.g. "2022":

Using some fake random data to mimic your real data:

library(ggplot2)

set.seed(123)

calories_data <- data.frame(
  ActivityDay <- rep(c("4/1", "4/10", "5/11", "5/1"), 3),
  Id = rep(1:3, each = 4),
  Calories = runif(12, 1000, 3000)
)

calories_data$ActivityDay <- as.Date(paste("2022", calories_data$ActivityDay, sep = "/"), format = "%Y/%m/%d")

ggplot(calories_data, aes(x= ActivityDay, y=Calories, group=Id, color = Id))+
  geom_line() +
  scale_x_date(date_breaks = "5 day", date_labels = "%m/%d")

stefan
  • 90,330
  • 6
  • 25
  • 51