【问题标题】:Reversing axis of class date课程日期的反转轴
【发布时间】:2019-08-23 07:25:14
【问题描述】:

我正在尝试反转绘图的 y 轴。现在该列属于date 类。可以通过添加 scale_y_reverse()scale_y_continuous(trans = "reverse) 来反转数字列,但我似乎无法弄清楚如何从上到下:2005, 2006, 2007我无法将日期列转换为数字,因为我在原始图中的月份有注释层。

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 

剧情:

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

编辑

我也不能get this answer to work,因为我的专栏属于date,而不是POSIXct

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

【问题讨论】:

标签: r ggplot2


【解决方案1】:

您可以创建一个新变量,其中年份为整数:

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

没有润滑,使用Year = as.numeric(format(date, "%Y"))

【讨论】:

  • 查看我的解释为什么我不能将值更改为年。
  • 这个解决方案中的值没有改变,我添加了一个临时值来绘制年份。您仍然可以将日期变量用于绘图中的其他图层。此解决方案确实符合您问题中的标准。
猜你喜欢
  • 2020-02-05
  • 1970-01-01
  • 2011-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多