Reputation: 337
I have a very simple dataset, such as:
df <- tibble("FID" = c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2),
"NDVI" = c(0.5, 0.55, 0.2, 0.3, 0.4, 0.5, 0.5, 0.5, 0.5, 0.55,
0.7, 0.72, 0.3, 0.35, 0.45, 0.50, 0.60, 0.65, 0.7, 0.7),
"days" = c(-36, -60, 0, 30, 60, 90, 100, 120, 140, 200,
-36, -60, 0, 30, 60, 90, 100, 120, 140, 200))
> df
# A tibble: 20 x 3
FID NDVI days
<dbl> <dbl> <dbl>
1 1 0.5 -36
2 1 0.55 -60
3 1 0.2 0
4 1 0.3 30
5 1 0.4 60
6 1 0.5 90
7 1 0.5 100
8 1 0.5 120
9 1 0.5 140
10 1 0.55 200
11 2 0.7 -36
12 2 0.72 -60
13 2 0.3 0
14 2 0.35 30
15 2 0.45 60
16 2 0.5 90
17 2 0.6 100
18 2 0.65 120
19 2 0.7 140
20 2 0.7 200
I would like to plot those points by FID
type and then add a regression line. This line though, would be only for points where days > 0. So it would be somehow to combine these 2 plots:
df %>% ggplot(aes(x = days, y = NDVI)) +
geom_point(aes(color = as.factor(FID), fill = as.factor(FID)),alpha=0.5, shape=21, size=5)
and
df %>% filter(days > 0) %>% ggplot(aes(x = days, y = NDVI)) +
geom_smooth(aes(color = as.factor(FID)), method="lm",se=TRUE)
I haven't been able to find how to add to the first graph a regression line (such as the second graph) under a certain condition (in this case days > 0).
Upvotes: 0
Views: 25
Reputation: 333
The cool thing about ggplot is that you can completely ignore the arguments in ggplot()
and pass them directly into your geom_*
.
So, you can do things like this:
ggplot() +
geom_point(data = df, mapping = aes(x = days, y = NDVI, color = as.factor(FID), fill = as.factor(FID)), alpha=0.5, shape=21, size=5) +
geom_smooth(data = filter(df, days > 0), mapping = aes(x = days, y = NDVI, color = as.factor(FID)), method="lm",se=TRUE)
Which would result in the following plot:
Upvotes: 2