11

我有一个栅格地图,我想使用 ggplot2 使用连续比例和标记的等值线绘制它。

为此,我正在使用 directlabels 包,并且接近于获得我想要的东西,但我无法在同一张地图上同时获得图例和标记的等值线

以下代码重现了我的问题:

install.packages(c('ggplot2', 'directlabels'))
library('ggplot2')
library('directlabels')
df <- expand.grid(x=1:100, y=1:100)
df$z <- df$x * df$y

# Plot 1: this plot is fine but without contours    
p <- ggplot(aes(x=x, y=y, z=z), data = df) + 
     geom_raster(data=df, aes(fill=z)) +
     scale_fill_gradient(limits=range(df$z), high = 'white', low = 'red')
p

# Plot 2: This plot adds the isolines but no labels and it also adds a second legend for level which I don't want
p <- p + geom_contour(aes(colour = ..level..), color='gray30', na.rm=T,     show.legend=T)
p

# Plot 3: This plot has the labeled isolines but it removes the z legend that I want to show
direct.label(p, list("bottom.pieces", colour='black'))

情节 1 在此处输入图像描述

情节 2 在此处输入图像描述

情节 3 在此处输入图像描述

我想在背景中有彩色光栅,侧面有颜色图例,顶部有标记的等值线。有没有办法做到这一点?

还有一种方法可以将标签放置在等值线的中间而不是底部或顶部?

提前致谢

巴勃罗

4

1 回答 1

18

首先,解决与传说有关的问题。

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

在此处输入图像描述

定位标签的选项并不多。一种可能是angled.boxes,但fill颜色可能不太好。

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

在此处输入图像描述

fill颜色更改为透明(使用此处的代码.

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

在此处输入图像描述

并将标签移出轮廓线:

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

在此处输入图像描述

于 2016-07-02T02:36:38.640 回答