How to cluster points around a center in ggplot

Viewed 167

I have a data frame with a small number of coordinate locations, but several observations at each location. I want to plot each observation, but since the coordinates are the same, they overlap. Example data is provided below

library(ggplot2)
data <- data.frame(lon = c(rep(-100, 15), rep(-98, 10), rep(-96, 8)),
                   lat = c(rep(50, 15), rep(58, 10), rep(46, 8)),
                   n = runif(33, 0, 300))
ggplot(data=data, aes(x=lon, y=lat, color=n)) + 
  geom_point()

Instead of having the points overlap, I want all of them to be clustered around the lat-lon coordinates provided. I have tried using jitter, however, the points are too scattered. I am looking for them to be in a (somewhat) circular cluster. How would I go about this?

Thanks!

2 Answers

A couple of options:

  1. Quick and simple: Use the width and height arguments of position_jitter to control the spread of points, this will require some trial and error attempts to get the required look.

  2. Taking your question literally modifying the lat and long of points to create a circle around the actual lat and long, for a bit of fun.

Option 1

library(ggplot2)

ggplot(data=data, aes(x=lon, y=lat, color=n)) + 
  geom_point(position = position_jitter(width = 0.15, height = 0.75, seed = 123))

Option 2

library(ggplot2)
library(dplyr)

# controls the spread of points
radius <- 0.5

data1 <- 
  data %>% 
  mutate(point = c(rep("a", 15), rep("b", 10), rep("c", 8))) %>% 
  group_by(point) %>% 
  mutate(point_id = row_number(),
         x_offset = sin(point_id*2*pi/max(point_id)) * radius,
         y_offset = cos(point_id*2*pi/max(point_id)) * radius,
         lon_mod = lon + x_offset,
         lat_mod = lat + y_offset)
         
# need to keep the x and y axis to the same scale to avoid distortion of the  points
# you could even apply a minimal jitter to these points if you felt it improves the appearance.
         
ggplot(data1, aes(lon_mod, lat_mod, color=n)) + 
  geom_point()+
  coord_fixed()

Created on 2021-07-12 by the reprex package (v2.0.0)

We could use geom_jitter

ggplot(data=data, aes(x=lon, y=lat, color=n))  +
    geom_jitter()

enter image description here

To modify geom_jitter use width and height to shape your cluster like:

ggplot(data=data, aes(x=lon, y=lat, color=n))  +
    geom_jitter(width = 0.15, height = 0.35)

enter image description here

Related