R ggplot geom_text消除了背景-错误吗?

时间:2019-02-08 03:18:32

标签: r ggplot2 geom-text

当我尝试用标签突出显示数据时,我发现ggplot2 :: geom_text()有问题。我的MWE说明了这种情况。定义图后,我从阶段1添加theme(),为面板着色并绘制背景。红色/绿色用于强调。在阶段2中添加标签时,plot.background变为白色,面板背景变为默认的灰色。这是我在做什么吗,是ggplot2的未记录功能,还是一个bug?

 require(ggplot2)

 SESnow <- data.frame(Year=c(1978,1988,1995,2000,2013,2017), 
                 Snow=c(355.9,322.1,329.1,303.6,318.5,304.0))

p <- ggplot(SESnow, aes(x=Year, y=Snow, fill=Snow)) +
geom_col(width=1)  + 
scale_fill_gradient(low="blue", high="red",  limits=c(0,400)) +
theme(axis.title.y=element_text(angle=0)) +
ggtitle("Yearly Total Snowfall (inch)") + 
labs(subtitle = "Copper City 2019", 
   caption="Source: Keweenaw County", 
   x="Snow Season") +
theme(legend.position="none")

#phase#1
p + theme( panel.background = element_rect(fill = "green",
                                       colour = "black",
                                       size = 0.5, linetype = "solid"),
       plot.background = element_rect(fill = "blue",
                                      colour = "black",
                                      size = 0.5, linetype = "solid"),
       axis.text.x = element_text(colour="grey20",size=11, vjust=1,
                                   margin=margin(t=0,b=0),face="bold"),
       axis.text.y = element_text(colour="grey20",size=11,  hjust=1,
                                   margin=margin(t=10,b=10),face="bold") )

#phase#2
p + geom_text(data=SESnow, aes(label = Snow, fill=NULL ),  y = SESnow$Snow + 20.0, 
        label=format(SESnow$Snow, digits=2), size=3, fontface="bold",
        color="black")

还请注意,如果您在阶段2之后运行阶段1,则标签会消失,因此此功能是一致的。如何获得带有标签和彩色背景的图?

1 个答案:

答案 0 :(得分:1)

答案很简单。您正在生成两个图,而不是一个。如果要使用相同的绘图并在以后进行修改,则需要将绘图存储在p中。


#phase#1
p <- p + theme( panel.background = element_rect(fill = "green",
                                       colour = "black",
                                       size = 0.5, linetype = "solid"),
       plot.background = element_rect(fill = "blue",
                                      colour = "black",
                                      size = 0.5, linetype = "solid"),
       axis.text.x = element_text(colour="grey20",size=11, vjust=1,
                                   margin=margin(t=0,b=0),face="bold"),
       axis.text.y = element_text(colour="grey20",size=11,  hjust=1,
                                   margin=margin(t=10,b=10),face="bold") )

#phase#2
p + geom_text(data=SESnow, aes(label = Snow, fill=NULL ),  y = SESnow$Snow + 20.0, 
        label=format(SESnow$Snow, digits=2), size=3, fontface="bold",
        color="black")

将该值分配给p,然后再次使用。这样可以解决问题。

编辑:我正在附上图表。我想这就是您想要的。enter image description here