Charles Santana
Charles Santana

Reputation: 140

Plotting a bar plot with X-axis defined as a time series in ggplot2

I have a tibble with 3 columns, representing the date of observations of 3 different variables (a, b, c).

I want to depict a bar plot using ggplo2, in which the X-axis represents the time. Independently on the time-span of my data, I want the X-axis to represent always the whole month (from day 1 to day 31, let's say).

test <- tibble(date=c("1/1/1","1/1/1","2/1/1","2/1/1","2/1/1","5/1/1","5/1/1","5/1/1"),
            variable=c("a","b","a","b","c","a","b","c"),
            observation=c(0.4,0.6,0.3,0.3,0.4,0.2,0.5,0.3))

ggplot(test, aes(x=as.Date(date), y=observation, fill=variable)) +
    geom_bar(position = "stack", stat = "identity") + 
    scale_x_date(date_breaks = "1 day", 
                 labels = date_format("%d/%m/%Y")) + 
theme(text = element_text(size=6), 
      axis.text.x = element_text(angle=90, hjust=1))

However, I can not read the X-axis information in my resulting plot. Should I use other functions instead of scale_x_date to define my X-axis?

enter image description here

Upvotes: 2

Views: 2020

Answers (1)

Marcelo Ventura
Marcelo Ventura

Reputation: 599

You need to use the option format= within as.Date() so that 5/1/1 can be read as January 5th, 2001 (as intended) instead of January 1st, 2005 (as is currently hapening).

tibble(
    date =
        c(
            "1/1/1", "1/1/1", "2/1/1", "2/1/1", 
            "2/1/1", "5/1/1", "5/1/1", "5/1/1"
        ) %>%
        as.Date(format = "%d/%m/%y"),
    variable = c("a", "b", "a", "b", "c", "a", "b", "c"),
    observation = c(0.4, 0.6, 0.3, 0.3, 0.4, 0.2, 0.5, 0.3)
) %>%
    ggplot(aes(x = date, y = observation, fill = variable)) +
    geom_bar(position = "stack", stat = "identity") + 
    scale_x_date(
        date_breaks = "1 day", 
        labels = date_format("%d/%m/%Y")
    ) + 
    theme(
        text = element_text(size = 6), 
        axis.text.x = element_text(angle = 90, hjust = 1)
    )

Notice I use as.Date(..., format = "%d/%m/%y") within your tibble() so that the legend becomes less poluted.

How the graphic should look

Upvotes: 2

Related Questions