How to nicely annotate a ggplot2 (manual)

前端 未结 3 1337
逝去的感伤
逝去的感伤 2020-11-30 18:38

Using ggplot2 I normally use geom_text and something like position=jitter to annotate my plots.

However - for a nice plot I of

相关标签:
3条回答
  • 2020-11-30 19:26

    I had a similar problem and solved it with JD Long answer. But as a results of ggplot2 updating to version 0.9.0 I noticed that all geom_text()calls rendered somewhat blurred on the plots.

    Thanks to kohske I discovered that this code

    ggplot(data2, aes(x=time, y=value, group=type, col=type))+
    geom_line()+
    geom_point()+
    theme_bw() +
    geom_text(aes(7, .9, label="correct color", color="NA*")) +
    geom_text(aes(15, .6, label="another correct color!", color="MVH")) 
    

    plots the geom_text nrow(data2)times!

    The correct way for supplying data to geom_text is building a different data.frame holding coordinates, labels and colors for the strings you want to be plotted:

    data2.labels <- data.frame(
      time = c(7, 15), 
      value = c(.9, .6), 
      label = c("correct color", "another correct color!"), 
      type = c("NA*", "MVH")
      )
    
    ggplot(data2, aes(x=time, y=value, group=type, col=type))+
      geom_line()+
      geom_point()+
      theme_bw() +
      geom_text(data = data2.labels, aes(x = time, y = value, label = label))
    
    0 讨论(0)
  • 2020-11-30 19:35

    If you use geom_text() instead of annotate() you can pass a group color to your plot:

    ggplot(data2, aes(x=time, y=value, group=type, col=type))+
    geom_line()+
    geom_point()+
    theme_bw() +
    geom_text(aes(7, .9, label="correct color", color="NA*")) +
    geom_text(aes(15, .6, label="another correct color!", color="MVH")) 
    

    So using annotate() it looks like this: alt text http://www.cerebralmastication.com/wp-content/uploads/2010/03/before.png

    then after using geom_text() it looks like this: alt text http://www.cerebralmastication.com/wp-content/uploads/2010/03/after.png

    0 讨论(0)
  • 2020-11-30 19:39

    These days there are packages adding labeling:

    1. geom_dl from the directlabel package with automatic data filtering to avoid repeated labels and
    2. geom_label_repel and geom_text_repel from package ggrepel make labels that try to avoid sitting on top of the data or each other and which in the case of geom_label_repel have a boundary and a non-transparant background.
    0 讨论(0)
提交回复
热议问题