这是上一个关于获取一些自定义错误栏的问题的后续。
- 情节的外观就是我所需要的,所以不要担心仅仅对此发表评论(尽管很高兴听到其他帮助的意见)
- 因为这些图是在循环中生成的,并且实际上只有在满足条件时才会添加误差线,所以我不能简单地预先合并所有数据,所以为了本练习的目的,假设绘图数据和误差线数据来自不同的dfs。
我有一个ggplot
,我尝试使用不同的数据框向其中添加一些错误栏。当我调用该图时,它说它无法从父图中找到 y 值,即使我只是尝试使用新数据添加误差线。我知道这一定是语法错误,但我很难过......
首先让我们生成数据和绘图
library(ggplot2)
library(scales)
# some data
data.2015 = data.frame(score = c(-50,20,15,-40,-10,60),
area = c("first","second","third","first","second","third"),
group = c("Findings","Findings","Findings","Benchmark","Benchmark","Benchmark"))
data.2014 = data.frame(score = c(-30,40,-15),
area = c("first","second","third"),
group = c("Findings","Findings","Findings"))
# breaks and limits
breaks.major = c(-60,-40,-22.5,-10, 0,10, 22.5, 40, 60)
breaks.minor = c(-50,-30,-15,-5,0, 5, 15,30,50)
limits =c(-70,70)
# plot 2015 data
ggplot(data.2015, aes(x = area, y = score, fill = group)) +
geom_bar(stat = "identity", position = position_dodge(width = 0.9)) +
coord_flip() +
scale_y_continuous(limit = limits, oob = squish, minor_breaks = breaks.minor,
breaks = breaks.major)
调用绘图 (c) 会产生预期的漂亮绘图,现在让我们设置误差线并尝试将它们作为新图层添加到绘图“c”中
# get the error bar values
alldat = merge(data.2015, data.2014, all = TRUE, by = c("area", "group"),
suffixes = c(".2015", ".2014"))
alldat$plotscore = with(alldat, ifelse(is.na(score.2014), NA, score.2015))
alldat$direction = with(alldat, ifelse(score.2015 < score.2014, "dec", "inc"))
alldat$direction[is.na(alldat$score.2014)] = "absent"
#add error bars to original plot
c <- c+
geom_errorbar(data=alldat, aes(ymin = plotscore, ymax = score.2014, color = direction),
position = position_dodge(width = .9), lwd = 1.5, show.legend = FALSE)
当我现在调用 c 时,我得到
"Error in eval(expr, envir, enclos) : object 'score' not found"
当我只想让它覆盖geom_errorbar
使用第二个 alldat 数据框时,为什么它会查找 data.2015$score?
编辑* 我尝试使用 alldata$plotscore 和 alldat$score.2014 (我确信这是不好的做法)为误差条指定 ymin/ymax 值,它会绘图,但条形图的位置/输出错误与情节顺序(例如交换,而不是在基准条上等)