scale_date位于顶部和底部ggplot2

时间:2018-01-22 13:16:19

标签: r ggplot2

scale_date()函数集接受顶部或底部(水平刻度)或右或左(垂直刻度)的刻度位置。但是它缺少允许辅助轴的scale_continuous(sec.axis)(比如把时间范围放在顶部和底部)。

以下是生成日期的代码:图表底部:

library(data.table)
library(ggplot2)
set.seed(123)

foo <- data.table(day = rep(seq(as.Date("2018-01-01"), as.Date("2018-01-30"), by="days"), 3),
                       var = c(rep("v1", 30), rep("v2", 30), rep("v3", 30)),
                       value = round(rnorm(90)*90))

ggplot2::ggplot(data = foo, ggplot2::aes(x = day, y = value, color = var)) + 
  ggplot2::geom_line() +
  ggplot2::ggtitle("Demo example",
                   subtitle = "random values") +
  ggplot2::scale_x_date(date_labels = "%Y%m%d",
                        breaks = seq(from = min(foo$day), to = max(foo$day), length.out = 5),
                        position = "bottom") +
  ggplot2::facet_grid(var ~ ., scales = "free") +  
  ggplot2::theme(legend.position = "top",
                 legend.title = ggplot2::element_blank(),
                 legend.direction = "horizontal",
                 plot.title = ggplot2::element_text(hjust = 0.5),
                 plot.subtitle = ggplot2::element_text(hjust = 0.5))

输出如下: scale_date at bottom 我有很多时间序列图,我正在以堆叠的方式绘制。这使得用户需要滚动才能看到时间尺度(不是很好的用户体验)。所以我想在顶部和底部都有时间刻度。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

为了完整起见,这里是代码(礼貌@axeman):

library(data.table)
library(ggplot2)
set.seed(123)

foo <- data.table(day = rep(seq(as.Date("2018-01-01"), as.Date("2018-01-30"), by="days"), 3),
                       var = c(rep("v1", 30), rep("v2", 30), rep("v3", 30)),
                       value = round(rnorm(90)*90))

ggplot(data = foo[, day1 := as.numeric(day)], aes(x = day1, y = value, color = var)) + 
  geom_line() +
  ggtitle("Demo example",
                   subtitle = "random values") +
  scale_x_continuous(sec.axis = dup_axis(), breaks = seq(from = min(foo$day1),
                                                to = max(foo$day1), length.out = 5),
                              labels = function(breaks) {lubridate::as_date(breaks)}) +
  facet_grid(var ~ ., scales = "free") +  
   theme(legend.position = "top",
                  legend.title = element_blank(),
                  legend.direction = "horizontal",
                  plot.title = element_text(hjust = 0.5),
                  plot.subtitle = element_text(hjust = 0.5))