0

I am exploring a dataset of goals (goals/minute here) across years (1986-2023) for both the men's and women's side of the game in this sport. I want to visually explore subsets of the data (here <=2009 and >2009) for both game disciplines.

What I've tried is this

ggplot(WMGoalsAll,aes(x=GoalsMin,fill=Discipline))+
  geom_histogram(data= ~subset(., Year >"2014"),aes(y=..count..),
                 binwidth=0.02,colour="black",fill="tomato3",position=position_dodge2(preserve="single"))+ 
  geom_histogram(data= ~subset(., Year<="2014"),aes(y=..count..),
                 binwidth=0.02,position="dodge",colour="black",fill="powderblue")+
  facet_grid(Discipline~.,scales="free")+
  scale_x_continuous(breaks=seq(0,0.3,0.02))+theme_light()+theme(axis.text.x=element_text(angle=90,vjust=0.5))

and this gives me just the figure I want Freq goals/min

... except as you can see I can't work out how to use the "position="dodge"", or one of its variations, to get the bars in each facet to sit alongside each other instead of on top. I have made subsets of the data to build separate figures and then put them together with grid.arrange but I feel the comparisons aren't as clear as they are with facet_grid or facet_wrap. Any help on how to do this gratefully received.

stefan
  • 90,330
  • 6
  • 25
  • 51
Eccles
  • 1

1 Answers1

0

To achieve your desired result use the complete dataset, use only one geom_histogram and instead of subsetting map the condition by which you want to split your data on the fill aesthetic. Afterwards you could set your desired fill colors via scale_fill_manual.

Using some fake random example data:

set.seed(123)

WMGoalsAll <- data.frame(
  Year = sample(c(2010, 2020), 100, replace = TRUE),
  Discipline = sample(c("Men", "Women"), 100, replace = TRUE),
  GoalsMin = runif(100, 0, .3)
)

library(ggplot2)

ggplot(WMGoalsAll, aes(x = GoalsMin)) +
  geom_histogram(
    aes(fill = Year > 2014),
    binwidth = 0.02, colour = "black",
    position = position_dodge2(preserve = "single")
  ) +
  scale_x_continuous(breaks = seq(0, 0.3, 0.02)) +
  scale_fill_manual(values = c("tomato3", "powderblue")) +
  facet_grid(Discipline ~ ., scales = "free") +
  theme_light() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

stefan
  • 90,330
  • 6
  • 25
  • 51