Home > Mobile >  Annotate plot with geom_circle(scale of x and y are different)
Annotate plot with geom_circle(scale of x and y are different)

Time:10-04

I am trying to annotate a specific area of data with geom_circle(), but the package drew an ellipse instead of a circle; It seems inherit.aes argument isn’t helping me to adjust the scale of the circle.

df = data.frame(index = 1:1000, data = runif(1000))
ggplot(df)   aes(x = index, y = data)   
  geom_point()   
  geom_circle(aes(x0=200, y0=0.4, r=3), inherit.aes=F)

enter image description here

I am expecting to get something like:

enter image description here

CodePudding user response:

You either need an ellipse, or a custom grob annotation:

df = data.frame(index = 1:1000, data = runif(1000))

ggplot(df)   aes(x = index, y = data)   
  geom_point()   
  geom_ellipse(aes(x0 = 200, y0 = 0.4, a = diff(range(index)) * 0.1,
                   b = diff(range(data)) * 0.1, angle = 0), col = "red") 

enter image description here

CodePudding user response:

As you want to add an annotation I would suggest to switch to ggforce::geom_mark_circle instead of using geom_circle which according to the docs

... will only produce a true circle if ggplot2::coord_fixed() is used.

In contrast ggforce::geom_mark_circle is meant to

annotate sets of points via circles.

and makes it easy to add the annotation via the label aes and offers a lot of options to style the annotation:

library(ggplot2)
library(ggforce)

set.seed(123)

df <- data.frame(index = 1:1000, data = runif(1000))

ggplot(df)  
  aes(x = index, y = data)  
  geom_point()  
  geom_mark_circle(aes(x = 200, y = 0.4, label = "Annotation"), 
                   radius = unit(15, "mm"), color = "red", size = 2, 
                   label.colour = "red", con.colour = NA, label.fill = NA,
                   label.buffer = unit(5, "mm"))

ggplot(df)  
  aes(x = index, y = data)  
  geom_point()  
  geom_mark_circle(aes(x = 200, y = 0.4, label = "Annotation"), 
                   radius = unit(15, "mm"), color = "red", size = 2, 
                   con.colour = "red", con.cap = unit(0, "mm"),
                   label.colour = "red", label.buffer = unit(5, "mm"))

  • Related