簡體   English   中英

R將圖例和直接標記添加到ggplot2等高線圖中

[英]R adding legend and directlabels to ggplot2 contour plot

我有一個柵格地圖,我想使用連續比例使用ggplot2繪制,並在其上標記為等值線。

為此,我使用直接標簽包,並接近得到我想要的但我無法在同一地圖上同時獲得圖例和標記的等值線

以下代碼重現了我的問題:

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 在此輸入圖像描述

我希望在背景中有彩色光柵,側面是彩色圖例,頂部是標記的等值線。 有沒有辦法做到這一點?

還有一種方法可以將標簽放在等值線的中間而不是底部或頂部嗎?

提前致謝

巴勃羅

首先,解決與傳說有關的問題。

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

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM