我更新了@tonytonov 的答案以不干扰默认的 X 轴。它仍然作为轴实现,但实现了自己的“标题”比例,并将用户提供的标题属性(如字体大小和颜色)与使轴不可见所需的默认属性正确合并。此版本隐藏轴而不假定特定的背景颜色。该函数后面有三个示例。
library(ggvis)
# ggvis lacks a plot title function, so add one.
# based on clever hack by tonytonov
# http://stackoverflow.com/a/25030002/1135316
add_title <- function(vis, ..., properties=NULL, title = "Plot Title")
{
# recursively merge lists by name
# http://stackoverflow.com/a/13811666/1135316
merge.lists <- function(a, b) {
a.names <- names(a)
b.names <- names(b)
m.names <- sort(unique(c(a.names, b.names)))
sapply(m.names, function(i) {
if (is.list(a[[i]]) & is.list(b[[i]])) merge.lists(a[[i]], b[[i]])
else if (i %in% b.names) b[[i]]
else a[[i]]
}, simplify = FALSE)
}
# default properties make title 'axis' invisible
default.props <- axis_props(
ticks = list(strokeWidth=0),
axis = list(strokeWidth=0),
labels = list(fontSize = 0),
grid = list(strokeWidth=0)
)
# merge the default properties with user-supplied props.
axis.props <- do.call(axis_props, merge.lists(default.props, properties))
# don't step on existing scales.
vis <- scale_numeric(vis, "title", domain = c(0,1), range = 'width')
axis <- ggvis:::create_axis('x', 'title', orient = "top", title = title, properties = axis.props, ...)
ggvis:::append_ggvis(vis, "axes", axis)
}
# add title with default X axis.
iris %>%
ggvis(x = ~Petal.Width) %>%
layer_points(y = ~Petal.Length, fill = ~Species) %>%
add_title(title = "Petal.Width vs. Petal.Length")
# Add title with overridden X axis
iris %>%
ggvis(x = ~Petal.Width) %>%
layer_points(y = ~Petal.Length, fill = ~Species) %>%
add_axis("x", title = "X-axis!!!!", title_offset=40,
properties = axis_props(title=list(fontSize=16),
labels = list(fontSize = 12))) %>%
add_title(title = "Petal.Width vs. Petal.Length")
# Change the font size of the title.
iris %>%
ggvis(x = ~Petal.Width) %>%
layer_points(y = ~Petal.Length, fill = ~Species) %>%
add_title(title = "Petal.Width vs. Petal.Length",
properties = axis_props(title=list(fontSize=20)))