【问题标题】:scale_date in top as well in bottom ggplot2 [duplicate]ggplot2 顶部和底部的 scale_date [重复]
【发布时间】:2018-01-22 13:16:18
【问题描述】:

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))

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

【问题讨论】:

  • 如果您提供a complete minimal reproducible example 来回答您的问题,我们更有可能为您提供帮助。我们可以轻松地学习和工作的东西。我们可以用来向您展示如何回答您的问题。
  • this issue,并在副本中接受的答案。

标签: r ggplot2


【解决方案1】:

为了完整起见,这里是代码(@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))

【讨论】:

    猜你喜欢
    • 2016-02-03
    • 2011-10-04
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    相关资源
    最近更新 更多