Home > OS >  How to find if a point is inside a specific zone in a plot?
How to find if a point is inside a specific zone in a plot?

Time:09-17

I have created the below example plot using ggplot2.

Example plot

The plot area is divided into various zones (SD, TC, CC, CCS) between the gray lines. I know the equations of each of these gray lines. I have also plotted my data What I would like to do is to find the zone where each data point is plotted, so I can divide them into categories and e.g. give them different colors for each zone. Does anyone have any idea? Thanks a lot in advance.

EDIT I added code to reproduce a simple example.

# load libraries
library(tidyverse)

# sample data
sample_data <- 
    tibble(
        x = c(8, 8, 8, 8, 8, 0),
        y = c(5, 10, 20, 50, 100, 100)
    )

# names of zones
zoning_data <-
  tibble(
    x = c(
      18,
      18,
      0,
      18
    ),
    y = c(
      70,
      25,
      600,
      600
    ),
    label = c(
      "CC",
      "CCS",
      "SD",
      "TC"
    )
  )

# plot
ggplot(
  data = sample_data,
  aes(
    x,
    y
  )
)  
  # points
  geom_point()  
  scale_x_continuous(
    expand = c(0, 0),
    minor_breaks = NULL,
    breaks = c(
      seq(-2, 20, by = 2)
    )
  )  
  scale_y_continuous(
    trans = "log10",
    expand = c(0, 0),
    minor = c(
      seq(1, 10, by = 1),
      seq(10, 100, by = 10),
      seq(100, 1000, by = 100)
    )
  )  
  coord_cartesian(
    xlim = c(-2, 20),
    ylim = c(1, 1000),
    expand = c(0, 0)
  )  
  # equations for zoning lines
  geom_function(
    fun = function(x) ((x - 1.05) * 5)^1.0526,
    xlim = c(1.31, 20)
  )  
  geom_function(
    fun = function(x) ((x - 1.1) * 1.5)^1.0989,
    xlim = c(2.82, 20)
  )  
  geom_function(
    fun = function(x) x,
    xlim = c(-2, 20)
  )  
  # zoning names
  geom_text(
    data = zoning_data,
    aes(
      x = x,
      y = y,
      label = label
    )
  )  
  # theme
  theme(aspect.ratio = 1)

CodePudding user response:

It's difficult to answer your question without a minimal reproducible example, but perhaps you can adapt this approach to your dataset:

library(tidyverse)

# Using the 'diamonds' example dataset
data(diamonds)
diamonds %>%
  ggplot(aes(x = carat, y = price))  
  geom_point()  
  coord_cartesian(ylim = c(0, 20000))

# example equations:
# price = 7000 * carat - 3000
# price = 7050 * carat - 1750

# Create a new variable ("zone")
# and categorise each data point
# using mutate and case_when
diamonds %>%
  mutate(zone = case_when(price <= 7000 * carat - 3000 ~ "zone 1",
                          price > 7000 * carat - 3000 & price < 7050 * carat - 1750 ~ "zone 2",
                          price >= 7050 * carat - 1750 ~ "zone 3")) %>%
  ggplot(aes(x = carat, y = price))  
  geom_point(aes(colour = zone))  
  coord_cartesian(ylim = c(0, 20000))

Created on 2021-09-15 by the reprex package (v2.0.1)

  • Related