R ggplot geom_text 消除背景——错误?

R ggplot geom_text wipes out background--bug?

当我尝试使用标签突出显示我的数据时,我发现 ggplot2::geom_text() 存在问题。我的 MWE 说明了这种情况。定义绘图后,我从阶段#1 添加 theme() ,它为面板和绘图背景着色。 red/green 用于强调。在第 2 阶段添加标签时,plot.background 变为白色,面板背景变为默认灰色。这是我正在做的事情,这是 ggplot2 的一个未记录的功能,还是一个错误?

 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 标签消失,则此功能是一致的。如何获得带有标签和彩色背景的绘图?

答案很简单。您正在生成两个图而不是一个。如果要使用相同的绘图并在以后修改它,则需要将绘图存储在 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。这将解决问题。

编辑:我附上图表。我想这就是你想要的。