R向ggplot2等高线图添加图例和直接标签

标签 r ggplot2 legend direct-labels

我有一个栅格 map ,我想使用 ggplot2 绘制它,使用连续比例并在其顶部标记等值线。

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

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

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 enter image description here

图 2 enter image description here

图 3 enter image description here

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

还有没有办法将标签放置在等值线的中间而不是底部或顶部?

提前致谢

巴勃罗

最佳答案

首先,解决与图例有关的问题。

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

enter image description here

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

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

enter image description here

填充颜色更改为透明(使用 here 中的代码。

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

enter image description here

并将标签移离轮廓线:

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

enter image description here

关于R向ggplot2等高线图添加图例和直接标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38154679/

相关文章:

java - XLConnect 包可以与 Java 8 一起使用吗?

r - 如何将 lubridate as_datetime 函数与 dplyr mutate 和 case_when 函数结合使用?

r - 在 R 中使用 pheatmap 自动分类和添加注释

r - 将 ggerrorplot 中表示均值的点更改为一条线

reporting-services - SSRS 根据条件隐藏图例中的项目

r - R图例在情节中的位置

r - 从矩阵中选择特定的行序列

r - 具有分组依据和分面的堆积条形图

r - R 中非线性关系的外推 (ggplot2)

Pandas 饼图图删除楔形上的标签文本