Reputation: 191
I found an issue with ggplot2::geom_text() when I attempt to highlight my data with labels. My MWE illustrates the situation. After I define the plot I add the theme() from phase#1 which colors the panel and plot backgrounds. The red/green is for emphasis. When the labels are added in phase#2, the plot.background goes to white and the panel background to the default grey. Is this something I'm doing, is this an undocumented feature of ggplot2, or is this a 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")
Also note that if you run phase#1 after phase#2 the labels disappear, so this feature is consistent. How do I get a plot with labels and colored background?
Upvotes: 2
Views: 393
Reputation: 340
The answer is simple. You are generating two plots instead of one. You need to store the plot in p
if you want to use the same plot and modify it later.
#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")
Assign the value to p
before you use it again. This will solve the issue.
Edit: I am attaching the graph. I guess this is what you wanted.
Upvotes: 1