R adding legend and directlabels to ggplot2 contour plot

浪尽此生 提交于 2019-11-30 12:39:59
Sandy Muspratt

First, fixing the issue to do with the legends.

library(ggplot2)
library(directlabels)

df <- expand.grid(x=1:100, y=1:100)
df$z <- df$x * df$y

p <- ggplot(aes(x=x, y=y, z=z), data = df) + 
     geom_raster(data=df, aes(fill=z), show.legend = TRUE) +
     scale_fill_gradient(limits=range(df$z), high = 'white', low = 'red') + 
     geom_contour(aes(colour = ..level..)) +
     scale_colour_gradient(guide = 'none') 

p1 = direct.label(p, list("bottom.pieces", colour='black'))
p1

There aren't too many options for positioning the labels. One possibility is angled.boxes, but the fill colour might not be too nice.

p2 = direct.label(p, list("angled.boxes"))
p2

To change the fill colour to transparent (using code from here.

p3 = direct.label(p, list("far.from.others.borders", "calc.boxes", "enlarge.box", 
      box.color = NA, fill = "transparent", "draw.rects"))
p3

And to move the labels off the contour lines:

p4 = direct.label(p, list("far.from.others.borders", "calc.boxes", "enlarge.box", 
      hjust = 1, vjust = 1, box.color = NA, fill = "transparent", "draw.rects"))
p4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!