Search code examples
rggplot2

Plotting points and arc on same ggplot


I am trying to overlay some random points and an arc using ggplot2, but can't seem to achieve both simultaneously.

Here is my code:

library(ggplot2)
library(ggforce)

# Generate random data
x <- runif(20)
y <- runif(20)
df <- data.frame(x = x, y = y)

# Plot points and quarter circle
ggplot(df, aes(x = x, y = y)) +
geom_point(size = 3) +
geom_arc(
  aes(x0 = 0, y0 = 0,   
      r = 1,            
      start = 0,       
      end = pi / 2),   
  color = "red",       
  size = 1             
) 

I think it's a really simple fix. Any ideas?


Solution

  • By default layers inherit the mappings from the base ggplot() call. The problem is your geom_arc is inheriting the x and y mappings. You can turn that off with inherit.aes=. But you are also bound to the same data so you are drawing an arch for every point in df. You can pass a NULL dataset to the layer as well,

    ggplot(df, aes(x = x, y = y)) +
      geom_point(size = 3) +
      geom_arc(
        aes(x0 = 0, y0 = 0,   
            r = 1,            
            start = 0,       
            end = pi / 2),   
        color = "red",       
        size = 1, inherit.aes = FALSE
      ) 
    

    That gives plot with arc