guyabel
guyabel

Reputation: 8366

Connecting position_dodge points from geom_point

I have data that is cross-classified by three variables, similar to this...

library(tidyverse)

d0 <- mtcars %>%
  group_by(cyl, am, vs) %>%
  summarise(ave_wt = mean(wt)) %>%
  ungroup() %>%
  complete(cyl, am, vs) %>%
  replace_na(list(ave_wt = 0)) %>%
  mutate_if(names(.) %in% names(.)[1:3], as.factor)
d0
# # A tibble: 12 x 4
#       cyl     am     vs   ave_wt
#    <fctr> <fctr> <fctr>    <dbl>
#  1      4      0      0 0.000000
#  2      4      0      1 2.935000
#  3      4      1      0 2.140000
#  4      4      1      1 2.028286
#  5      6      0      0 0.000000
#  6      6      0      1 3.388750
#  7      6      1      0 2.755000
#  8      6      1      1 0.000000
#  9      8      0      0 4.104083
# 10      8      0      1 0.000000
# 11      8      1      0 3.370000
# 12      8      1      1 0.000000

I am trying to get a plot with these points...

ggplot(data = d0, 
       mapping = aes(x = am, y = ave_wt, colour = vs, group = cyl)) +
 geom_point(position = position_dodge(0.5)) 

enter image description here

... joined up for each vs - am combination, as below but with the lines a bit straighter (lines not plotted with ggplot here).

enter image description here

All my attempts thus far do not work...

ggplot(data = d0, 
       mapping = aes(x = am, y = ave_wt, colour = vs, group = cyl)) +
 geom_point(position = position_dodge(0.5)) +
 geom_line()
 # geom_line(mapping = aes(group = interaction(vs, am)))
 # geom_line(mapping = aes(group = interaction(vs, am)),
 #           position = position_dodge(0.5))
 # geom_line(position = position_dodge(0.5))
 # geom_path(position = position_dodge(0.5),
 #           mapping = aes(group = interaction(vs, am)))

Upvotes: 3

Views: 682

Answers (1)

jazzurro
jazzurro

Reputation: 23574

Here is one way for you. The idea was to create the final output based on your output. I used the data frame behind your graphic. It contains all information we need. I sorted the data and grouped the data points into four groups, which is done in mutate(). Then, I drew the graphic below.

library(dplyr)
library(ggplot2)

foo <- ggplot(data = d0, 
              aes(x = am, y = ave_wt, colour = vs, group = cyl)) +
       geom_point(position = position_dodge(0.5)) 

temp <- as.data.frame(ggplot_build(foo)$data[1])

arrange(temp, colour, x) %>%
mutate(whatever = rep(1:4, each = 3)) %>%
ggplot(aes(x = x, y = y, color = factor(colour, levels = c("#F8766D", "#00BFC4")),
       group = whatever)) +
geom_line() +
geom_point() +
scale_x_continuous(breaks = c(1,2), minor_breaks = NULL, labels = c(0, 1)) +
labs(x = "am", y = "ave_wt") +
scale_color_discrete(name = "vs", labels = c(0, 1)) 

enter image description here

Upvotes: 3

Related Questions