I want to make one plot with 3 scatterplots, but I have no idea how. I can plot them seperately as:
library(dplyr)
library(ggplot2)
kat %>%
filter(Sex %in% c("F")) %>%
ggplot(aes(x = Bwt, y = Hwt)) geom_point() facet_wrap("Sex")
kat %>%
filter(Sex %in% c("M")) %>%
ggplot(aes(x = Bwt, y = Hwt)) geom_point() facet_wrap("Sex")
kat %>%
ggplot(aes(x = Bwt, y = Hwt)) geom_point() facet_wrap("Sex")
I have searched in previous Stack Overflow topics, but without any luck.
CodePudding user response:
Since you want two facet to be "individual Sex" and one to be "all", then we can duplicate the data:
library(dplyr)
library(ggplot2)
mtcars %>%
mutate(cyl = "All") %>%
bind_rows(mutate(mtcars, cyl = as.character(cyl))) %>%
ggplot(aes(mpg, disp))
geom_point()
facet_wrap(~ cyl)
This premise works regardless of your plotting preference (e.g., scatterplot or histogram).
The intermediate mutate(mtcars, cyl=as.character(cyl))
is because the duplicated data has a string for cyl
whereas the original data is integer
; since your "Sex"
column is already character
, you likely won't need that intermediate as.character
. If they are factor
s, however, you may need to proactively manage the levels of the factor to include "All"
(or whatever string you prefer).
CodePudding user response:
That is what I understand what you want. Starting from your three plots and then putting them together here with patchwork
.
library(MASS)
data(cats)
library(dplyr)
library(ggplot2)
library(patchwork)
p1 <- cats %>%
filter(Sex %in% c("F")) %>%
ggplot(aes(x = Bwt, y = Hwt)) geom_point() facet_wrap("Sex")
p2 <- cats %>%
filter(Sex %in% c("M")) %>%
ggplot(aes(x = Bwt, y = Hwt)) geom_point() facet_wrap("Sex")
p3 <- cats %>%
ggplot(aes(x = Bwt, y = Hwt)) geom_point() facet_wrap("Sex")
(p1 | p2)/
p3