想法是生成围绕一条特定线的多条线和带状图。
以下是数据:
x <- data.table(a = 1:10, y = runif(10, 1, 2), z = runif(10, 1, 2))
x[,y_h:=y+.2]
x[,y_l:=y-.2]
x <- melt(x, id.vars = ("a"), variable.factor = F)
这会生成折线图:
ggplot(x[variable %in% c("y", "z")], aes(x = a, y = value, color = variable)) +
geom_line() +
theme_minimal()
这会生成功能区图:
ggplot(data = dcast(x[variable %in% c("y_h", "y_l")], a ~ variable, value.var = "value"),
aes(x = a, ymin = y_l, ymax = y_h)) +
geom_ribbon(alpha = .3) +
theme_minimal()
两者结合会产生错误:
ggplot(x[variable %in% c("y", "z")], aes(x = a, y = value, color = variable)) +
geom_line() +
theme_minimal() +
geom_ribbon(data = dcast(x[variable %in% c("y_h", "y_l")], a ~ variable, value.var = "value"),
aes(x = a, ymin = y_l, ymax = y_h), alpha = .3)
Error in eval(expr, envir, enclos) : object 'value' not found
我知道多行需要长格式的数据,而功能区需要宽格式的列才能输入ymin
和ymax
。此错误消息实际上无助于确定问题的原因。
答案 0 :(得分:1)
在发布问题后,我自己得到了答案。
下面:
ggplot(data = dcast(x[variable %in% c("y_h", "y_l")], a ~ variable, value.var = "value")) +
geom_ribbon(aes(x = a, ymin = y_l, ymax = y_h), alpha = .3) +
geom_line(data = x[variable %in% c("y", "z")], aes(x = a, y = value, color = variable)) +
theme_minimal()
我想问题是在aes()
调用下geom_ribbon()
全局设置ggplot()
个变量。显然它会混淆后续的aes()
,即使您为每个geom
明确定义它们。但是,错误消息仍然让我偏离了正确的道路。