0

In the plot below, I show values of $R^2$ from a set of models fit to subsets of a data set using dplyr and broom. I'd like to connect the points by lines, or else draw horizontal lines to each point, as in a traditional dot plot. How can I do this?

enter image description here

Code

library(dplyr)
library(ggplot2)
library(gapminder)
library(broom)

# separate models for continents
models <- gapminder %>%
    filter(continent != "Oceania") %>%
    group_by(continent) %>%
    do(mod = lm(lifeExp ~ year + pop + log(gdpPercap), 
                data=.)
      )
models %>% glance(mod)

gg <- 
    models %>%
    glance(mod) %>%
    ggplot(aes(r.squared, reorder(continent, r.squared))) +
        geom_point(size=4) +
        ylab("Continent") 
gg

I tried adding geom_line(), and can't understand how I use a group aesthetic in this context

gg + geom_line()
geom_path: Each group consists of only one observation. Do you need to adjust
the group aesthetic?


gg + geom_line(aes(group=continent))

Alternatively, I tried geom_line(), as below, without success:

> gg + geom_hline(yintercept=levels(continent))
Error in levels(continent) : object 'continent' not found
user101089
  • 3,756
  • 1
  • 26
  • 53
  • `gg + geom_line(aes(group = 1))` works fine! Basically, points are connected _within_ groups, and by setting group to 1 all points will be connected. Not sure if the lines are informative, however. Get horizontal lines using `gg + geom_segment(aes(xend = 0, yend = ..y..))`. – Axeman Mar 26 '18 at 13:51
  • Ah! Beautiful, and more informative than connected lines. The `yend=..y..` was what I was missing. – user101089 Mar 26 '18 at 14:36

1 Answers1

1

This works, but I would question the use of a connecting line. Generally such lines suggest a logical progression to the sequence of observations, e.g. number of events over time. Is there such an order in these data?

gg <- 
  models %>%
  glance(mod) %>%
  mutate(group = 1) %>% 
  ggplot(aes(r.squared, reorder(continent, r.squared), group = group) ) +
  geom_path() + 
  geom_point(size=4) +
  ylab("Continent") 
gg
r.bot
  • 5,309
  • 1
  • 34
  • 45
  • The ordering is based on R^2 values, achieved by using `reorder(continent, r.squared)`. I hadn't considered `geom_path()` here, but this connects the points in alphabetic order, not what I want. Ah!! `geom_line()` does what I want here. – user101089 Mar 26 '18 at 13:46