dbnomics.R 2.56 KB
Newer Older
1
2
#' DBnomics ggplot2 theme
#'
3
#' \code{dbnomics} is a simple ggplot2 theme for drawing nicer graphics. We do not
4
#' recommend to use it. It has been included in the package to avoid errors
5
#' when reproducing the vignette examples.
6
#'
7
8
9
#' @param color_palette Character string (default \code{"Set1"}) to change the
#' default color palette. If you want to use the default palette, set it to
#' \code{NULL}.
10
#' @param ... Arguments to be passed to the function \code{ggplot2::theme}.
11
12
13
#' 
#' @examples
#' \dontrun{
14
#' library(magrittr)
15
16
#' library(ggplot2)
#' 
17
#' rdb("IMF", "WEO:2019-10", query = "France current account balance percent") %>%
18
19
20
21
22
#'   ggplot(aes(x = period, y = value, color = series_name)) +
#'   geom_line(size = 1.2) +
#'   geom_point(size = 2) +
#'   dbnomics()
#' }
23
#' @author Sebastien Galais
24
#' @export
25
dbnomics <- function(color_palette = "Set1", ...) {
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
  code <- paste(
    "  ggplot2_ok <- try(utils::packageVersion('ggplot2'), silent = TRUE)",
    "  if (inherits(ggplot2_ok, 'try-error')) {",
    "    stop(",
    "      'Please install the package ggplot2 to use dbnomics().',",
    "      call. = FALSE",
    "    )",
    "  }",
    "  result <- list(",
    "    ggplot2::scale_x_date(expand = c(0, 0)),",
    "    ggplot2::scale_y_continuous(",
    "      labels = function(x) { format(x, big.mark = ' ') }",
    "    ),",
    "    ggplot2::xlab(''),",
    "    ggplot2::ylab(''),",
    "    ggplot2::theme_bw(),",
    "    ggplot2::theme(",
    "      legend.position = \"bottom\", legend.direction = 'vertical',",
    "      legend.background = ggplot2::element_rect(",
    "        fill = 'transparent', colour = NA",
    "      ),",
    "      legend.key = ggplot2::element_blank(),",
    "      panel.background = ggplot2::element_rect(",
    "        fill = 'transparent', colour = NA",
    "      ),",
    "      plot.background = ggplot2::element_rect(",
    "        fill = 'transparent', colour = NA",
    "      ),",
    "      legend.title = ggplot2::element_blank()",
    "    ),",
    "    ggplot2::theme(...),",
    "    ggplot2::annotate(",
    "      geom = 'text', label = 'DBnomics <https://db.nomics.world>', ",
    "      x = structure(Inf, class = 'Date'), y = -Inf,",
    "      hjust = 1.1, vjust = -0.4, col = 'grey', ",
    "      fontface = 'italic'",
    "    )",
    "  )",
    "  if (!is.null(color_palette)) {",
    "    check_argument(color_palette, 'character')",
    "    result <- c(",
    "      result,",
    "      list(ggplot2::scale_color_brewer(palette = color_palette))",
    "    )",
    "  }",
    "  result",
    sep = "\n"
73
  )
74
  eval(parse(text = code))
75
}