Search code examples
rplotstatisticsdata-visualizationscatter-plot

Giving different colors to the dots that are in different intervals on a scatter plot in R


I am a beginner in R and would like to give different colors to the dots in my scatter plot, between 0 -> 0.4, 0.4 ->0.8 and 0.8 -> 1 in my x-axis. i have googled a lot but was not able to find hints for the solution.

i am using this code for the plot :

ggplot(xlim=1, ylim=1,)+geom_point(data=df,aes(x1,y1))+
  geom_circle(aes(x0 = x0, y0 = y0 ,r = r,colour=cb), data = circ_kv) +
  coord_fixed(xlim=c(0,1),ylim=c(0,1))

all help or hints are very much appreciated!

this is the scatter plot i am working with


Solution

  • Something like this?

    library(tidyverse)
    
    set.seed(1337)
    
    data <- tibble(
      x = runif(300),
      y = runif(300)
    )
      
    data %>%
      mutate(
        # distance to origin
        r = sqrt(x**2 + y**2),
        r_group = case_when(
          r < 0.4 ~ "group 1",
          r < 0.8 ~ "group 2",
          r < 1.0 ~ "group 3"
        )
      ) %>%
      ggplot(aes(x,y, color = r_group)) +
        geom_point() +
        coord_fixed()
    

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