Home > Blockchain >  How to have a factor outside the axis for an arrow in ggplot
How to have a factor outside the axis for an arrow in ggplot

Time:02-11

I want to make an annotation with an arrow that goes outside a plot in ggplot. Using geom_curve changes the order of the factor, and I do not understand why.

Here is the example: let's consider the following plot:

df <- data.frame(ID = factor(c("A","B","C"),level = c("AA","B","C","A")),
           y = 1:3)

ggplot(df,aes(ID,y,color = ID)) 
  geom_point() 
  coord_flip(clip = "off") 
  scale_x_discrete(breaks = c("B","C","A"))

enter image description here

I want to keep the order of the vertical axis (B,C,A), and have an arrow pointing at the first point but from above the plot. I thus want to ass a factor before A that goes outside the plot:

ggplot(df,aes(ID,y,color = ID)) 
  geom_point() 
  geom_curve(data = data.frame(ID = factor("AA",level = c("AA","B","C","A")),
                               ID_end = "A",
                               y = 2,y_end = 1),
             aes(x = ID,xend = ID_end,
                 y = y ,yend = y_end),
             curvature = -.1,
             arrow =arrow(length = unit(2, "mm"),type = "closed"),
             color = "grey20" ,size = .2) 
  coord_flip(clip = "off") 
  scale_x_discrete(breaks = c("B","C","A"))

enter image description here

Here the vertical axis has the factors reordered, although I specified the same order in geom_curve. My arrow lies in the middle instead of being on the top/outside the plot.

How can I solve this problem?

CodePudding user response:

Does this help you? The arrow is not really "outside" the plot, but the order on the axis is maintained the way you want

df <- data.frame(
  ID = factor(c(1,2,3), labels=c("B","C","A")),
  y =c(2,3,1)
)

curvedata = data.frame(
  ID = 4, 
  ID_end = 3,
  y = 2,y_end = 1)

ggplot(df,aes(ID,y,color = ID)) 
  geom_point() 
  geom_curve(data=curvedata,
             aes(x = ID,xend = ID_end,
                 y = y ,yend = y_end),
             curvature = -.1,
             arrow =arrow(length = unit(2, "mm"),type = "closed"),
             color = "grey20" ,size = .2) 
  coord_flip(clip = "off")

arrow_on_top

CodePudding user response:

If you want to manually add a few things to a graph, use annotate(geom = "XXX") rather than geom_XXX with a custom data =.

Also, factor levels get converted to integers. It is easier to specify the integer value, rather than forcing the factor levels.

ggplot(df,aes(ID,y,color = ID)) 
    geom_point() 
    annotate(geom = "curve", x = -1L, xend = 1, y = 2, yend = 1,
             curvature = -.1,
             arrow =arrow(length = unit(2, "mm"),type = "closed"),
             color = "grey20" ,size = .2)  
    coord_flip(clip = "off") 
    scale_x_discrete(breaks = c("B","C","A"))
  • Related