我有数据:
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
行之前,图形生成正常为什么添加该行会使“距离”消失?
答案 0 :(得分:2)
我认为这是因为geom_rect
从最初的x
电话中获取y
和ggplot
美学(即使它不需要或理解它们) )并且无法在background
中找到它们。
为什么不直接输入xstart
,xend
等而不是创建background
?
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"))
注意 - 我接受了填充&#39;出于&#39; aes&#39;在geom_rect
中,以便将填充颜色解释为文字颜色&#39;灰色&#39;而不是发生的因素,使其具有值&#34;灰色&#34 ; (然后ggplot将使用它通常用于因子的任何默认颜色方案)。我想你实际上可以从那里的aes
geom_rect
电话中取出所有。