Overlay two scatter plots into just one (with ggplot)
I have 2 data frames one for males and one for females (the variables are the same, crc
and maxilla
). From each of these df I generated two graphs. Now I'm trying to combine them into just one chart, but as they have number of different lines I can't do it.
The DFS are as follows:
alometria_M_max = (data.frame(crc_M, maxilla_M))
crc_M maxilla_M
1 5.897154 1.398717
2 6.102559 1.560248
3 6.173786 1.640937
4 6.001415 1.515127
5 5.926926 1.388791
6 5.926926 1.458615
7 5.863631 1.558145
8 5.960232 1.528228
9 5.880533 1.437463
10 6.082219 1.547563
11 5.973810 1.521699
12 5.918894 1.458615
13 5.855072 1.423108
14 5.808142 1.283708
alometria_F_max = (data.frame(crc_F, maxilla_F))
crc_F maxilla_F
1 6.198479 1.576915
2 6.295266 1.701105
3 6.418365 1.884035
4 6.393591 1.818077
5 6.120297 1.665818
6 6.142037 1.633154
7 6.139885 1.615420
8 5.855072 1.543298
9 5.913503 1.665818
10 6.165418 1.479329
11 6.107023 1.607436
12 6.214608 1.710188
13 6.171701 1.684545
Charts
plot_M <- ggplot(alometria_M_max, aes(x=crc_M, y= maxilla_M)) +
geom_point(color="green") +
theme_bw() +
theme_classic() +
geom_smooth(method = "lm", se= FALSE, color= "green")
plot_F <- ggplot(alometria_F_max, aes(x=crc_F, y= maxilla_F)) +
geom_point(color="red") +
theme_bw() +
theme_classic() +
geom_smooth(method = "lm", se= FALSE, color= "red")
Anyone, please, have any idea how do I put these two graphs together into just one, with the slope lines of the regression visible?
1 answers
Like almost everything in ggplot2
, the best way to solve graph display problems is by organizing the data frame. In case, I suggest it be a data frame only, with three columns: crc
, maxilla
and grupo
. The group column will indicate which crc
and maxilla
belong to each group, in case M or F.
Below I show how my solution turned out:
crc_M <- c(5.897154, 6.102559, 6.173786, 6.001415,
5.926926, 5.926926, 5.863631, 5.960232,
5.880533, 6.082219, 5.973810, 5.918894,
5.855072, 5.808142)
maxilla_M <- c(1.398717, 1.560248, 1.640937, 1.515127,
1.388791, 1.458615, 1.558145, 1.528228,
1.437463, 1.547563, 1.521699, 1.458615,
1.423108, 1.283708)
crc_F <- c(6.198479, 6.295266, 6.418365, 6.393591,
6.120297, 6.142037, 6.139885, 5.855072,
5.913503, 6.165418, 6.107023, 6.214608,
6.171701)
maxilla_F <- c(1.576915, 1.701105, 1.884035, 1.818077,
1.665818, 1.633154, 1.615420, 1.543298,
1.665818, 1.479329, 1.607436, 1.710188,
1.684545)
alometria <- data.frame(crc = c(crc_M, crc_F),
maxilla = c(maxilla_M, maxilla_F),
grupo = rep(c("M", "F"),
c(length(crc_M), length(crc_F))))
library(ggplot2)
ggplot(alometria, aes(x = crc, y = maxilla, colour = grupo, group = grupo)) +
geom_point() +
geom_smooth(aes(colour = grupo), method = "lm", se = FALSE)
#> `geom_smooth()` using formula 'y ~ x'
Created on 2020-11-04 by the reprex package (v0.3.0)