Change point shapes based on longitude and latitude range on gradient map

I have a gradient map with the following code:

library(ggplot2)
ggplot(data = world) +
  geom_sf() +
  coord_sf(xlim = c(125.8, 129.8), ylim = c(33.0, 38.95), expand = FALSE) + 
  geom_point(aes(Lon, Lat,color=meanrow),data=master,size=3) +  
  scale_color_gradient(low = "green", high="red") + 
  labs(title = "Mean Annual Precipitation from 2001-2020", x = "Longitude", y="Latitude", color="Annual Precipitation (mm)") + 
  #geom_text(aes(Lon, Lat),data=master,label=master$Ename,nudge_y = .1,size=2.8)+
  geom_hline(yintercept=37, linetype="dashed", color="red") +
  geom_segment(x=127,y=33, xend=127, yend=37, linetype="dashed", color="red")

It looks like this:

Now what I want to do is to change the shapes of the points based on which sides of the dashed lines they are on. Is this possible to do via code easily because I anticipate that I will have to change the locations of the boundary lines often.

EDIT: Thanks to @danlooo’s help, I was able to do exactly what I wanted, and this is how it looks now:

x=master$Lon
y=master$Lat
x_intercept <- 127
y_intercept <- 37

shape=case_when(
  y > y_intercept ~ "top",
  y < y_intercept & x < x_intercept ~ "lower left",
  TRUE ~ "other")
ggplot(data = world) +
  geom_sf() +
  coord_sf(xlim = c(125.8, 129.8), ylim = c(33.0, 38.95), expand = FALSE) + 
  geom_point(aes(x=Lon, y=Lat,color=meanrow,shape=shape),data=master,size=3) +  
  scale_color_gradient(low = "green", high="red") + 
  labs(title = "Mean Annual Precipitation from 2001-2020", x = "Longitude", y="Latitude", color="Annual Precipitation (mm)") + 
  #geom_text(aes(Lon, Lat),data=master,label=master$Ename,nudge_y = .1,size=2.8)+
  geom_hline(yintercept=37, linetype="dashed", color="red") +
  geom_segment(x=127,y=33, xend=127, yend=37, linetype="dashed", color="red")

updated map

>Solution :

You can calculate the shape in a new column based on predefined thresholds, which will be also used in drawing the lines:

library(tidyverse)

y_intercept <- 1
x_intercept <- 5.5

iris %>%
  mutate(
    x = Sepal.Length,
    y = Petal.Width,
    shape = case_when(
      y > y_intercept & x > x_intercept ~ "top right",
      y > y_intercept & x < x_intercept ~ "top left",
      TRUE ~ "other"
    )
  ) %>%
  ggplot(aes(x, y)) +
  geom_point(aes(shape = shape), size = 5) +
  geom_vline(xintercept = x_intercept) +
  geom_hline(yintercept = y_intercept)

Created on 2022-05-04 by the reprex package (v2.0.0)

Leave a Reply