这是对之前有关获取自定义误差条的问题的后续。
首先让我们生成数据和图表。
当我现在调用c时,我会得到以下结果:
当我只想使用第二个alldat数据框覆盖geom_errorbar时,为什么它会寻找data.2015 $ score?编辑* 我已经尝试使用alldata $ plotscore和alldat $ score.2014指定误差条的ymin / ymax值(我确定这是不好的做法),它可以绘制,但条形的位置错误/与图形不一致(例如交换,位于基准条上等)。
- 图表的外观符合我的需求,因此不必担心仅针对此进行评论(但很乐意听取与其他帮助相关的意见)
- 由于这些图是在循环中生成的,而且只有在满足条件时才会添加误差线,所以我无法简单地将所有数据合并到前面,因此假设为此练习中的绘图数据和误差条数据来自不同的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)
调用plot(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"
当我只想使用第二个alldat数据框覆盖geom_errorbar时,为什么它会寻找data.2015 $ score?编辑* 我已经尝试使用alldata $ plotscore和alldat $ score.2014指定误差条的ymin / ymax值(我确定这是不好的做法),它可以绘制,但条形的位置错误/与图形不一致(例如交换,位于基准条上等)。
geom_errobar
继承了你在ggplot
中设置的全局美学中的y
美学,而变量score
不在第二个数据集中。要么在新数据集中将该列命名为score
(也许可以在merge
中尝试一下suffixes
参数),要么在geom_errorbar
的美学中使用y = score.2015
。 - aosmith