Reputation: 169
I have a base plot graph made of multiple lines that I would like to recreate in ggplot2 using smooth lines.
Data looks like this:
x1
ID P col Lat
86230 0.16666667 black 45.06
86230 0.57142857 black 45.42
86230 0.88235294 black 45.66
86230 1.00000000 black 45.87
96464 0.46428571 black 45.06
96464 0.50000000 black 45.42
96464 0.92857143 black 45.66
96464 1.00000000 black 45.87
97181 0.94736842 gray87 45.06
97181 0.87500000 gray87 45.42
97181 0.82352941 gray87 45.66
97181 0.33333333 gray87 45.87
101351 0.40000000 black 45.06
101351 1.00000000 black 45.42
101351 1.00000000 black 45.66
101351 1.00000000 black 45.87
102193 0.15789474 black 45.06
102193 0.66666667 black 45.42
102193 0.96875000 black 45.66
102193 1.00000000 black 45.87
102156 0.94736842 gray87 45.06
102156 1.00000000 gray87 45.42
102156 0.82142857 gray87 45.66
102156 0.10000000 gray87 45.87
Code:
plot(x1$Lat[1:4], x1$P[1:4], col="black",
type = "b", lwd = 3,
xlab = "Latitude", xaxt = 'n',cex.lab=1.25,
ylab = "Frequency",
pch = 8, cex = 1.0, main = "Transect B", ylim = c(0:1))
for (j in 1:548)
points(x1$Lat[(j*4)+1:4], x1$P[(j*4)+1:4],
col=tolower(x1$col[(j*4)+1]),
type = "b", lwd = 3, pch = 8, cex = 1)
axis(1, x1$Lat)
Get this graph: I would like to smooth all the black lines with a positive trend into one line and the gray lines into another smoothed line.
Using advice from a different post, I've tried:
x1 <- x1[1:548,2:4] ##dont ID
x1<- tbl_df(x1)
x1 <- x1 %>% gather(key, Value, -Lat)
pl <- ggplot(x1, aes(x = Lat, y = P, col = key)) + geom_line() +
geom_smooth(method = lm) + theme_classic()
p2 <- ggplot(x1, aes(x = Lat, y = P, col = col)) + geom_line() +
geom_smooth(method = lm) + theme_classic()
I'm sure there's an easy solution to this. Any help is appreciated.
Upvotes: 0
Views: 1958
Reputation: 16832
You can use geom_smooth
to make summary lines. The trick is how you group the data. In geom_line
, you want to group by ID, so each ID gets its own line. In geom_smooth
, you want to group by color, so that you get a line to represent all the IDs of each color. You can mess around with alpha, linetype, and line size to differentiate between the individual lines and the grouped lines; I used alpha & linetype to do this.
library(tidyverse)
ggplot(df, aes(x = Lat, y = P)) +
geom_line(aes(group = ID, color = col), alpha = 0.6) +
geom_smooth(aes(color = col), method = lm, linetype = 2, se = F, show.legend = F) +
scale_color_identity() +
theme_light()
Created on 2018-04-29 by the reprex package (v0.2.0).
Upvotes: 2