Reputation: 4940
I want to make a horizontal bar chart with dates on the x axis using ggplot. Here is the code I have:
df <- data.frame(patient= c('Harry','John'), pain_date = c( as.POSIXct('13-04-2000', format = '%d-%m-%Y'), as.POSIXct('12-02-2000', format = '%d-%m-%Y') ), agony_date = c(as.POSIXct('25-05-2000', format = '%d-%m-%Y'),as.POSIXct('21-05-2000', format = '%d-%m-%Y')), death_date = c(as.POSIXct('30-06-2000', format = '%d-%m-%Y'), as.POSIXct('23-11-2000', format = '%d-%m-%Y')))
ggplot(df, aes(x=patient)) +
geom_linerange(aes(ymin=pain_date, ymax=agony_date), color="red", size=5) +
geom_linerange(aes(ymin=agony_date, ymax=death_date), color="black", size=5) +
coord_flip()
The question is how to fix the limit from JAN to DEC and how to put a tick at every first day of a month?
I've tried several things like:
scale_x_datetime(major="months")
scale_x_datetime(lim = c(as.POSIXct("01-01-2000"), as.POSIXct("31-12-2000")))
but it gives me the following error message:
Erreur : Invalid input: date_trans works with objects of class Date only
Thanks for your help
Upvotes: 3
Views: 2238
Reputation: 22293
Summarizing the comments above, your code should look something like this:
require(scales)
df[, "pain_date"] <- as.Date(df[, "pain_date"])
df[, "agony_date"] <- as.Date(df[, "agony_date"])
df[, "death_date"] <- as.Date(df[, "death_date"])
ggplot(df, aes(x=patient)) +
geom_linerange(aes(ymin=pain_date, ymax=agony_date), color="red", size=5) +
geom_linerange(aes(ymin=agony_date, ymax=death_date), color="black", size=5) +
coord_flip() + scale_y_date(lim = c(as.Date("2000-01-01"), as.Date("2000-12-31")),
breaks=date_breaks(width = "1 month"))
Upvotes: 4