R将图例和直接标记添加到ggplot2等高线图中

时间:2016-07-01 22:39:21

标签: r ggplot2 legend direct-labels

我有一个栅格地图,我想使用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 enter image description here

情节2 enter image description here

情节3 enter image description here

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

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

提前致谢

巴勃罗

1 个答案:

答案 0 :(得分:15)

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

angled.boxes

enter image description here

定位标签的选项太多了。一种可能性是fill,但p2 = direct.label(p, list("angled.boxes")) p2 颜色可能不太好。

fill

enter image description here

要将p3 = direct.label(p, list("far.from.others.borders", "calc.boxes", "enlarge.box", box.color = NA, fill = "transparent", "draw.rects")) p3 颜色更改为透明(使用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

将标签移离轮廓线:

    func getNameOfUser(uid: String) -> String {
    var name: String = ""
    FIRAuth.auth()?.signInAnonymouslyWithCompletion() { (user, error) in
        self.ref = FIRDatabase.database().reference()
        self.ref!.child("users").child(uid).child("name").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
            name = snapshot.value! as! String
        }) { (error) in
            print(error.localizedDescription)
        }
    }
    return name
}

enter image description here