library(ggplot2)
library(dplyr)
# I guess this works only with >1.0.1
packageVersion("ggplot2")
## [1] '1.0.1.9003'
Define Stat/Geom
StatContourLabel <- ggproto(
"StatContourLabel",
Stat,
default_aes = aes(label = ..level..),
compute_group = function(..., digits = 1) {
StatContour$compute_group(...) %>%
group_by(level) %>%
summarise(x = nth(x, round(n() / 2)),
y = nth(y, round(n() / 2))) %>%
mutate(level = signif(level, digits = digits))
}
)
geom_contour_label <- function(mapping = NULL, data = NULL,
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, digits = 1, ...) {
layer(
data = data,
mapping = mapping,
stat = StatContourLabel,
geom = "text",
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
na.rm = na.rm,
digits = digits,
...
)
)
}
geom_labeled_contour <-
function(mapping = NULL, data = NULL, stat = "contour", position = "identity",
lineend = "butt", linejoin = "round", linemitre = 1, na.rm = FALSE,
show.legend = NA, inherit.aes = TRUE, digits = 1, ...) {
list(
geom_contour(
mapping, data, stat, position,
lineend, linejoin, linemitre, na.rm,
show.legend, inherit.aes, ...
),
geom_contour_label(
mapping, data,
position, na.rm, show.legend,
inherit.aes, digits, ...
)
)
}
Draw A Chart
N <- 60
x <- seq(0, 100, length=N)
d.cont <- data.frame(x=rep(x,N), y=rep(x,each=N))
d.cont <- transform(d.cont,
z.diff=x-y,
z.ratio=ifelse(x+y==0, 0.5, x/(x+y))
)
ggplot(d.cont, aes(x, y, z = z.diff)) +
geom_contour() +
geom_contour_label()

ggplot(d.cont, aes(x, y, z = z.diff / 1250)) +
geom_labeled_contour()
