Given a dataframe MenRG_Final
containing the following variables:
Name | Description |
---|---|
P1DistanceRun | Distance covered by the player |
PointNumber | Point number |
PointServer | Point server |
PointWinner | Point winner |
ServeDepth | Serve depth |
ServeNumber | Serve number |
ServeWidth | Serve direction |
Speed_KMH | Serve speed |
I would like to make the following plot with ggplot2
consisting in two geom_boxplot
with common legend and axis labels:
So far, I've been able to make this plot:
with this R code:
library(tidyverse)
library(patchwork)
theme_set(theme_minimal())
p1 <- ggplot(
MenRG_Final %>% filter(PointWinner == "Rafael Nadal"),
aes(x = PointServer, P1DistanceRun)
) +
geom_boxplot(aes(fill = ServeNumber)) +
labs(
title = "Nadal a gagné le point"
)
p2 <- ggplot(
MenRG_Final %>% filter(PointWinner == "Stan Wawrinka"),
aes(x = PointServer, P1DistanceRun)
) +
geom_boxplot(aes(fill = ServeNumber)) +
labs(
title = "Wawrinka a gagné le point",
) +
theme(
axis.text.y = element_blank(),
axis.ticks.y = element_blank()
)
(p1 + p2) + plot_layout(guides = "collect") & ylim(0, 60) & theme(legend.position = "top") & labs(x = "Serveur", y = "Distance Parcourue")
In particular, I'm wondering how can I:
If you want to play with the data, I made it available in the dataset folder here: https://github.com/Mathieu-R/ggplot2/tree/main
As outlined in the comments you could achieve your desired result easily and with less code by using facetting:
library(ggplot2)
theme_set(theme_minimal())
ggplot(
MenRG_Final,
aes(x = PointServer, P1DistanceRun)
) +
geom_boxplot(aes(fill = ServeNumber)) +
scale_fill_discrete(labels = c("Premier Service", "Deuxième Service")) +
facet_wrap(~PointWinner, labeller = labeller(
PointWinner = c(
"Rafael Nadal" = "Nadal a gagné le point",
"Stan Wawrinka" = "Wawrinka a gagné le point"
)
)) +
theme(legend.position = "top") +
labs(x = "Serveur", y = "Distance Parcourue", fill = NULL)