这是关于获取一些自定义误差线的上一个问题的后续问题。
- 情节的外观正是我所需要的,所以不必担心仅对此进行评论(不过很高兴听到其他帮助附带的意见)
- 因为这些图是在循环中生成的,并且误差线实际上仅在满足条件时才添加,所以我不能简单地预先合并所有数据,因此假设出于本练习的目的,图数据和误差线数据来自不同的数据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"
为什么它会查找 data.2015$score 当我只想它覆盖geom_errorbar
使用第二个 alldat 数据框?
编辑* 我尝试使用 alldata$plotscore 和 alldat$score.2014 指定误差线的 ymin/ymax 值(我确信这是不好的做法),它会绘制,但条形图位于错误的位置/输出与图的顺序(例如交换,在基准条上,等等)