2

I'm trying to reverse the y-axis of a plot. Now the column is of a class date. Numeric columns can be reversed by adding scale_y_reverse() or scale_y_continuous(trans = "reverse) but I can't seem to figure out how to get from top to bottom: 2005, 2006, 2007. I can't convert the date column to numeric because I've annotations layers on months in my original plot.

library(tidyverse)

df <- structure(list(date = structure(c(12784, 13149, 13514), class = "Date"), 
    nr = c(1.14192497730255, 0.719137012958527, 1.3783597946167
    )), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-3L), .Names = c("date", "nr"))

# A tibble: 3 x 2
  date          nr
  <date>     <dbl>
1 2005-01-01 1.14 
2 2006-01-01 0.719
3 2007-01-01 1.38 

Plot:

df %>%
  ggplot(aes(date, nr)) +
  geom_col() +
  coord_flip() +
  scale_x_date(date_labels = "%Y",
               date_breaks = "1 years") 

enter image description here

Edit

I also can't get this answer to work because my column is of class date and not POSIXct:

Error: Invalid input: time_trans works with objects of class POSIXct only

Tdebeus
  • 1,519
  • 5
  • 21
  • 43
  • 1
    https://gist.github.com/mikmart/bfbf62839fbdd162b4b88e6d43e0c858 – M-- Aug 22 '19 at 22:57
  • 2
    ```df %>% ggplot(aes(as.numeric(date), nr)) + geom_col() + coord_flip() + scale_x_reverse(labels = as.character(lubridate::year(df$date)), breaks = as.numeric(df$date))``` – M-- Aug 22 '19 at 23:02
  • Possible duplicate of [Reverse datetime (POSIXct data) axis in ggplot](https://stackoverflow.com/questions/43625341/reverse-datetime-posixct-data-axis-in-ggplot) – M-- Aug 22 '19 at 23:03
  • Could you add an example of the annotations you need to layer on? There might be workarounds that allow you to convert some aspects of the data – camille Aug 23 '19 at 05:05

1 Answers1

-1

You could create a new variable with the year as an integer:

library(lubridate)
df %>%
    mutate(Year = year(date)) %>%
    ggplot(aes(Year, nr)) +
    geom_col() +
    coord_flip() +
    scale_x_reverse()

Without lubridate, use Year = as.numeric(format(date, "%Y")).

Peter Prevos
  • 413
  • 4
  • 12
  • See my explanation why I can't change values to years. – Tdebeus Aug 22 '19 at 23:07
  • The values are not changed in this solution, I added a temporary value to plot years. You can still use the date variable for other layers in the plot. This solution does meet the criteria in your question. – Peter Prevos Aug 24 '19 at 00:41