我有数据:
Distance Average Standard.error CI
-300 0.9338864 0.01409078 0.02761792
-150 0.9339457 0.02097350 0.04110805
-50 0.9495119 0.01359277 0.02664183
50 0.8588988 0.03599673 0.07055359
150 0.8531203 0.03047781 0.05973651
300 0.7945437 0.05874081 0.11513199
我正在 ggplot2 中创建一个图表,到目前为止我的代码是:
ggplot(data = Test, aes(x = Distance, y = Average))+
geom_errorbar(aes(ymin = Average - CI, ymax = Average + CI), width = 5)+
geom_point(data = Test, aes(x = Distance, y = Average), stat = "identity",
point = 21, fill = "white")+
scale_x_continuous(breaks = seq(-300,300,100))+
scale_y_continuous(breaks = seq(0.6,1,0.05))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"),
axis.text.x = element_text(colour = "black"),
axis.text.y = element_text(colour= "black"))
我想在 x 轴上从 -300 到 0 的图表中添加灰色背景,因此我创建了此数据框:
background <- data.frame( xstart = 300, xend = 0, col = "grey")
然后将此行添加到图表的脚本中:
geom_rect(data = background, aes(xmin = xstart, xmax = xend, ymin = -Inf, ymax = Inf,
fill = col), alpha = 0.4)
所以图表的代码现在看起来像这样:
ggplot(data = Test, aes(x = Distance, y = Average))+
geom_rect(data = background, aes(xmin = xstart, xmax = xend, ymin = -Inf, ymax = Inf,
fill = col), alpha = 0.4)+
geom_errorbar(aes(ymin = Average - CI, ymax = Average + CI), width = 5)+
geom_point(data = Test, aes(x = Distance, y = Average), stat = "identity",
point = 21, fill = "white")+
scale_x_continuous(breaks = seq(-300,300,100))+
scale_y_continuous(breaks = seq(0.6,1,0.05))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"),
axis.text.x = element_text(colour = "black"),
axis.text.y = element_text(colour= "black"))
但是现在当我尝试生成图表时收到一条错误消息:
Error in eval(expr, envir, enclos) : object 'Distance' not found
在添加 geom_rect
行之前,图表生成得很好,为什么添加该行会使“距离”消失?
最佳答案
我认为这是因为 geom_rect
从最初的 ggplot
调用中获取了 x
和 y
美学(即使它不需要或理解它们)并且无法在背景
中找到它们。
为什么不直接输入xstart
、xend
等而不是创建背景
?
ggplot(data = Test, aes(x = Distance, y = Average))+
geom_rect(aes(xmin = 0, xmax = 300, ymin = -Inf, ymax = Inf),
fill = 'grey', alpha = 0.4)+
geom_errorbar(aes(ymin = Average - CI, ymax = Average + CI), width = 5)+
geom_point(data = Test, aes(x = Distance, y = Average), stat = "identity",
point = 21, fill = "white")+
scale_x_continuous(breaks = seq(-300,300,100))+
scale_y_continuous(breaks = seq(0.6,1,0.05))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"),
axis.text.x = element_text(colour = "black"),
axis.text.y = element_text(colour= "black"))
注意 - 我从geom_rect
中的“aes”中取出了“fill”,以便填充颜色被解释为文字颜色“grey”,而不是发生的一个因素 具有值“灰色”(然后 ggplot 将使用它通常用于因子的任何默认配色方案)。我认为您实际上可以从对 geom_rect
的 aes
调用中获取一切。
关于r - 添加 geom_rect 时对象消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31309120/