1
votes

I have a dodged bar chart generated from the mtcars dataset showing a histogram of gear vs cyl. I'd like to mark a particular make of car mark on the chart - the chart attached will illustrate this better. The code is doing what it should (points are placed in line with the x axis label cyl) but I'd like the points to align with the correct bar showing the number of gears instead. Any ideas please?

require(graphics)
carsraw <- mtcars

cars <- mtcars  %>% 
  select(cyl,gear) %>% 
  mutate(cyl=as.factor(cyl),gear=as.factor(gear)) %>% 
  group_by(cyl,gear) %>% 
  tally() %>% 
  rename(count=n)

Hornet <- mtcars %>% 
  add_rownames("model") %>% 
  filter(model %in% c("Hornet 4 Drive","Hornet Sportabout")) %>% 
  mutate(cyl=as.factor(cyl),gear=as.factor(gear)) %>% 
  mutate(count=7) %>% 
  select(model,cyl,gear,count)

(ggplot(data=cars)+
    aes(x=cyl,y=count,fill=gear) +
    geom_bar( position = "dodge", stat="identity")+
    geom_point(data=Hornet,size=5)+
    aes(x=cyl,y=count,fill=gear))

enter image description here

1

1 Answers

1
votes

You could try using position_nudge in this particular case, although it is a bit of a hack:

(ggplot(data=cars)+
    aes(x=cyl,y=count,fill=gear) +
    geom_bar( position = "dodge", stat="identity")+
    geom_point(data=Hornet,size=5, position = position_nudge(-0.25))+
    aes(x=cyl,y=count,fill=gear))

enter image description here

Edit

Given the comments by the OP, here is an alternative that changes the preparation of the data a little bit. What I am doing here is including the existance of the model in the group as a Hornet column in the summarise function (and adding NA for (cyl, gear) pairs that don't include the specific model). Additionally, you have to use group = gear and position = position_dodge(1):

library(tidyverse)    
cars <- mtcars  %>% 
    rownames_to_column("model") %>% 
    mutate(cyl=as.factor(cyl),gear=as.factor(gear)) %>% 
    group_by(cyl,gear) %>% 
    summarise(
        count = n(),
        Hornet = ifelse(
            any(model %in% c("Hornet 4 Drive","Hornet Sportabout")),
            7,
            NA
        )
    ) %>% ungroup()

cars %>% ggplot() + 
    geom_col(
        aes(
            x = cyl,
            y = count,
            fill = gear
        ),
        position = "dodge"
    ) +
    geom_point(
        aes(
            x = cyl,
            y = Hornet,
            group = gear
        ),
        na.rm = TRUE,
        position = position_dodge(1),
        size = 5
    )