Search code examples
rggplot2bar-chartdata-visualizationgeom-bar

How to convert continuous date into discete category?


I have a set a data which contains values from two different years but I haven't been able to set it into two discrete categories instead of a continual range of dates when plotting it.

enter image description here

If I try with scale_x_discrete, the year labels will altogether disappear.

library(ggplot2)
ggplot(df2018, aes(x = Year, y= Weight, fill = Year)) +
  geom_bar(stat = "identity") +
  coord_flip() +
  facet_wrap(~ Species, scale = "free_x") +
  scale_x_discrete("Year", labels = c("2018", "2019"))

How can I convert the Year column so that ggplot reads it as two different categories (i.e. year 2018 & 2019)?

Data:

structure(list(Species = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 
2L, 3L, 1L, 4L, 5L, 6L), .Label = c("Coralline", "Pocockiella", 
"Gigartina", "Ulva", "Colpomenia", "Sargassum"), class = "factor"), 
    Year = c(2018, 2018, 2018, 2018, 2018, 2018, 2019, 2019, 
    2019, 2019, 2019, 2019), Weight = c(0.83879, 1.61504, 2.32838, 
    6.25983, 8.77286, 115.48649, 0.046695, 0.1373982, 0.392931, 
    0.508436, 0.521956, 90.098115), Percent = c(0.614156130776106, 
    1.18252091399354, 1.70482343825805, 4.58340344080901, 6.42342630865946, 
    84.5583946581545, 0.0508869004261174, 0.149732702047923, 
    0.428205175529173, 0.554079282686656, 0.568812999225068, 
    98.186396971536)), row.names = c(NA, -12L), class = c("tbl_df", 
"tbl", "data.frame"))

Solution

  • Change year to factor class :

    library(dplyr)
    library(ggplot2)
    
    df %>%
      mutate(Year = factor(Year)) %>%
      ggplot() + aes(x = Year, y= Weight, fill = Year) +
      geom_bar(stat = "identity") +
      coord_flip() +
      facet_wrap(~ Species, scale = "free_x")
    

    enter image description here