Search code examples
rggplot2graphicsscale

How do I insert scales in my geom_area graphic?


I'm coding a graphic and I'm giving the scales Y that I want to plot, but when I plot it the scales is wrong. See it:

ggplot(pop_idade_escolar_americana, aes(x = Ano, y = De.0a5.anos)) +
  geom_area( fill="#69b3a2", alpha=0.4) +
  geom_line(color="#69b3a2", size=2) +
  geom_point(size=3, color="#69b3a2") +
  scale_y_continuous(breaks = c(10000, 11000, 13000, 14000),
                     labels = comma_format(big.mark = ".")) +
  labs(y = NULL,
       x = NULL) +
  hrbrthemes::theme_ipsum()

Plot: enter image description here


Solution

  • Use geom_ribbon instead of geom_area.

    The only differences between the two:

    geom Required aesthetics Defaults
    geom_ribbon x, ymin, ymax (none)
    geom_area x, y ymin=0 (and ymax=y)
    ggplot(pop_idade_escolar_americana, aes(x = Ano, y = De.0a5.anos)) +
      geom_ribbon(aes(ymin = -Inf, ymax = De.0a5.anos), fill="#69b3a2", alpha=0.4) +
      geom_line(color="#69b3a2", size=2) +
      geom_point(size=3, color="#69b3a2") +
      scale_y_continuous(breaks = c(10000, 11000, 13000, 14000),
                         labels = comma_format(big.mark = ".")) +
      labs(y = NULL,
           x = NULL) +
      hrbrthemes::theme_ipsum()
    

    The use of ymin = -Inf uses ggplot's default expansion of the axis, so it'll be "a little" below the minimum observed value. Some alternatives for defining ymin:

    • literal ymin = 9000 (may be inside or outside aes(..))
    • manual offset ymin = min(De.0a5.anos) - 500 (must be inside aes(..)), the offset may be nothing (just min(..)) if you desire