我曾经与ggplot2
制作互动情节,下面给出了代码。现在我想用ggvis
重现相同的情节,如下所示,与ggplto2
输出不同。如何使用ggvis
得到相同的情节?
library(ggplot2)
p <- qplot(as.factor(dose), len, data=ToothGrowth, geom = "boxplot", color = supp) + theme_bw()
p <- p + labs(x="Dose", y="Response")
p <- p + stat_summary(fun.y = mean, geom = "point", color = "blue", aes(group=supp))
p <- p + stat_summary(fun.y = mean, geom = "line", aes(group = supp))
p <- p + theme(axis.title.x = element_text(size = 12, hjust = 0.54, vjust = 0))
p <- p + theme(axis.title.y = element_text(size = 12, angle = 90, vjust = 0.25))
print(p)
library(ggvis)
ggvis(data=ToothGrowth, x= ~as.factor(dose), y= ~len, fill= ~supp, stroke = ~supp) %>%
layer_points(shape=~supp) %>%
layer_lines(fillOpacity=0)
答案 0 :(得分:7)
尝试在ggvis
中实现此问题时,基本问题是position = dodge
中没有ggplot2
选项,因此不同supp
值的框图无法在相同的x
坐标处绘制。因此,将x
轴编入as.factor(dose)
索引似乎不是一种选择。但是,我们可以做的是使用长度等于唯一剂量值数的整数索引,然后根据x
手动将数据的supp
位置向左或向右偏移。值:
library(ggvis)
library(dplyr)
d <- ToothGrowth
d$xpos <- as.integer(factor(d$dose)) + ifelse(d$supp == "OJ", -.2, .2)
因此我们现在可以使用x = ~xpos
在正确的位置绘制箱线图。下一步是定义数据,其中包含用于绘制由线连接的点的方法。
means <- d %>% group_by(dose, supp) %>% summarise(len = mean(len))
means$xpos <- as.integer(factor(means$dose))
means <- group_by(means, supp) # The grouping is needed for layer_paths()
现在可以获得图表
ggvis(d, x = ~xpos, y = ~len, stroke = ~supp) %>%
layer_boxplots() %>%
layer_points(data = means, fill := "blue") %>%
layer_paths(data = means)
现在我们遇到的问题是,图的x
位置将是1,2,3,而不是实际的剂量值。这不是很容易克服,因为add_axis()
无法重新标记轴刻度(同样,我们不能首先使用实际剂量值而不是1,2,3,因为那样会已经将箱形图放置在剂量值0.5和1处,与剂量值1和2处的剂量值相比更接近彼此。这可以通过不那么优雅的黑客来克服,即为每个单剂量值添加轴。函数add_axis()
提供了一种修改轴属性(包括标签)的方法,但它将对整个轴使用相同的标签,因为属性适用于整个轴。因此,通过为每个剂量值添加轴,我们可以逐个操作标签。这看起来像
ggvis(d, x = ~xpos, y = ~len, stroke = ~supp) %>%
layer_boxplots() %>%
layer_points(data = means, fill := "blue") %>%
layer_paths(data = means) %>%
add_axis("x", title = "Dose",
values = c(1, 1), # For some reason values of length 1 don't work...
properties = axis_props(labels = list(text = "0.5"))) %>%
add_axis("x", title = "",
values = c(2, 2),
properties = axis_props(labels = list(text = "1"))) %>%
add_axis("x", title = "",
values = c(3, 3),
properties = axis_props(labels = list(text = "2"))) %>%
add_axis("y", title = "Response")
或者,您可以为这些使用循环,这样您就不必一遍又一遍地输入相同的东西
labs <- data.frame(dose = unique(d$dose))
labs$xpos <- as.integer(factor(labs$dose))
v <- ggvis(d, x = ~xpos, y = ~len, stroke = ~supp) %>%
layer_boxplots() %>%
layer_points(data = means, fill := "blue") %>%
layer_paths(data = means) %>%
add_axis("x", title = "Dose", ticks = 0) %>%
add_axis("y", title = "Response")
for (i in 1:nrow(labs)) {
v <- add_axis(v, "x", title = "", values = rep(labs[i, "xpos"], 2),
properties = axis_props(labels = list(text = as.character(labs[i, "dose"]))))
}
最终结果如下所示