stat_contour,行上有数据标签

时间:2012-11-29 14:16:15

标签: r ggplot2

我想知道如何在ggplot2中获取轮廓上的数据标签。感谢

require(grDevices) # for colours

x <- seq(-4*pi, 4*pi, len = 27)
y <- seq(-4*pi, 4*pi, len = 27)
r <- sqrt(outer(x^2, y^2, "+"))

rx <- range(x <- 10*1:nrow(volcano))
ry <- range(y <- 10*1:ncol(volcano))
ry <- ry + c(-1, 1) * (diff(rx) - diff(ry))/2

plot(
    x = 0
  , y = 0
  , type = "n"
  , xlim = rx
  , ylim = ry
  , xlab = ""
  , ylab = ""
  )

contour(
    x = x
  , y = y
  , z = volcano
  , add = TRUE
  )

library(ggplot2)
library(reshape2)
volcano3d <- melt(volcano)
names(volcano3d) <- c("x", "y", "z")

# Basic plot
v <- ggplot(volcano3d, aes(x, y, z = z))
v + stat_contour()

2 个答案:

答案 0 :(得分:25)

使用直接标签包并从this

中挑选解决方案
# Basic plot
v <- ggplot(volcano3d, aes(x, y, z = z))
library(directlabels)
v2 <- v + stat_contour(aes(colour = ..level..))
direct.label(v2, method="bottom.pieces")

enter image description here

答案 1 :(得分:0)

这是一个已经回答的老问题,但是我做了很多等高线图,并且我认为使用包metR(https://rdrr.io/github/eliocamp/metR/f/vignettes/Visualization-tools.Rmd)可以更简单,更通用。该软件包具有geom_label_contour()函数,该函数提供了一种绘制轮廓标签的简便方法。还提供了许多绘制地图的功能。

library(ggplot2)
library(reshape2)
library(metR)
volcano3d <- melt(volcano)
colnames(volcano3d) <- c('x','y','z')

ggplot(data = volcano3d, aes(x=x,y=y,z=z)) + geom_contour() +
  geom_label_contour()