giacomoV giacomoV - 1 month ago 16
R Question

R - ggplot2 geom_line dodge

I am having trouble drawing "dodges"

line
on "dodged"
stacked bars
.

dt = mtcars %>% group_by(am, cyl) %>% summarise(m = mean(disp))
dt0 = dt[dt$am == 0, ]
dt1 = dt[dt$am == 1, ]

dt0 %>% ggplot(aes(factor(cyl), m, fill = factor(cyl))) + geom_bar(stat = 'identity', position = 'dodge') +
geom_point(data = dt1, aes(factor(cyl), m, colour = factor(cyl)), position=position_dodge(width=0.9), colour = 'black')


enter image description here

What I would like is to draw a line from the top of the stacked bar to the black points of each
cyl
.

dt0 %>% ggplot(aes(factor(cyl), m, fill = factor(cyl))) + geom_bar(stat = 'identity', position = 'dodge') +
geom_point(data = dt1, aes(factor(cyl), m, colour = factor(cyl)), position=position_dodge(width=0.9), colour = 'black') +
geom_line(data = dt1, aes(factor(cyl), m, colour = factor(cyl), group = 1), position=position_dodge(width=0.9), colour = 'black')


However, the
position=position_dodge(width=0.9)
dodge doesn't work here.

Any idea ?

Answer

This is much easier to accomplish if you reshape your summary data:

dt <- mtcars %>% 
    group_by(am, cyl) %>% 
    summarise(m = mean(disp)) %>% 
    spread(am, m)

    cyl        0        1
* <dbl>    <dbl>    <dbl>
1     4 135.8667  93.6125
2     6 204.5500 155.0000
3     8 357.6167 326.0000

While "0" and "1" are poor column names, they can still be used in aes() if you quote them in backticks. The calls to position_dodge() also become unnecessary:

dt %>% ggplot(aes(x = factor(cyl), y = `0`, fill = factor(cyl))) + 
    geom_bar(stat = 'identity') +
    geom_point(aes(x = factor(cyl), y = `1`), colour = 'black') +
    geom_segment(aes(x = factor(cyl), xend = factor(cyl), y = `0`, yend = `1`))

enter image description here