#check_answers(my_answers)

Question

Considere o gráfico criado de barras criado com o código abaixo:

library(ggplot2)

tickers <- c("PETR3.SA", "ITSA3.SA",
             "GRND3.SA", "GGBR3.SA",
             "EGIE3.SA", "USIM5.SA")

df_yf <- yfR::yf_get(tickers, 
                     "2020-01-01") 

df_tab <- df_yf |>
  dplyr::group_by(ticker) |>
  dplyr::summarise(
    total_ret = dplyr::last(cumret_adjusted_prices) - 1
    ) |>
  dplyr::arrange(total_ret)

p <- ggplot(df_tab, aes(x = reorder(ticker, total_ret),
                          y = total_ret,
                          fill = total_ret)) +
  geom_col(color = "white") + 
  theme_minimal() +
  coord_flip() + 
  labs(title = stringr::str_glue(
    "Performance de {length(tickers)} Ações Selecionadas"
    ),
       y = "Retorno Total",
       x = "Ticker")

Com base no código anterior, use as ferramentas de programação do R para, de forma automática, aplicar todas as possíveis combinações entre os temas:

e as paletas do colorspace

Adicionalmente:

  1. agrege todos os gráfico em um único arquivo com função cowplot::plot_grid
  2. salve a figura resultante como themes-and-palettes-demo.png, pasta documentos (atalho com ~). Defina o tamanho da figura como height = 30cm e width = 60cm. DICA: Caso a figura gravada sair com fundo transparente, abra-a em um navegador da web, tal como o Chrome ou firefox.

Solution

library(ggplot2)

plot_fct <- function(theme_str, palette, p) {

    this_theme <- eval(parse(text = theme_str))

    p <- p + 
      this_theme() +
      labs(
        subtitle = stringr::str_glue(
        "{theme_str} | {palette}"
        ),
        title = "Demonstração") +
      colorspace::scale_fill_binned_diverging(palette)

    return(p)
}

theme_fcts <- c(
  "ggplot2::theme_light",
  "hrbrthemes::theme_ipsum_es",
  "ggtech::theme_airbnb_fancy"
  )

palettes <- c(
  "Red-Green",
  "Green-Brown",
  "Tropic"
)

df_grid <- tidyr::expand_grid(
  theme_fcts,
  palettes
)

l_args <- list(
  theme_str = df_grid$theme_fcts, 
  palette = df_grid$palettes
)

l_p <- purrr::pmap(.l = l_args, .f = plot_fct, p = p)

p_grid <- cowplot::plot_grid(plotlist = l_p)

p_grid

ggsave("~/themes-and-palettes-demo.png", p_grid, height = 40, width = 60, units = "cm")

Meta-information

extype: string exsolution: r mchoice2string(c(TRUE, FALSE, FALSE, FALSE, FALSE), single = TRUE) exname: "programming" exshuffle: TRUE



msperlin/vdr documentation built on Nov. 25, 2022, 2:29 a.m.