rggplot2mlm

Why does using theme() in ggplot deletes my beforehand specified labs() command?


It seems to be the case that as soon as I call theme() in ggplot2 my previous labs() for the same plot gets deleted/overwritten. I surfed for 5 hours now and I do not see the solution. Does anyone see the reason why this happens? You would save my week.

This is my code:

#creating variables and store them in new data frame

rel_pred <- fitted(rel)
rel_resid <- residuals(rel)
data1 <- data.frame(rel_resid, rel_pred)`

#plot the data

plot1 <- ggplot(data1, aes(x=rel_pred,y=rel_resid)) + 
geom_point() + 
geom_hline(yintercept=0, colour='red') #so far so good, everything works

plot1 + labs(y="Residuals", x="Fitted Values SF-12 MCS", caption="Figure  
1. Residuals vs. fitted Values Model 1") #when I run this, it perfectly 
adds labels

Here comes the problem: as soon as I run theme() with whatever elements in there, it will make my previous labels disappear.

plot1 + theme(panel.background = element_rect(fill='transparent'),
plot.background = element_rect(fill='transparent'),
panel.border = element_blank(),
axis.line = element_line(colour="black", size=1),
axis.title.x = element_text(colour='black',size=6),
axis.title.y = element_text(colour='black', size=6),
plot.caption = element_text('Figure 1. Residuals vs. fitted Values Model   
1')
)

Solution

  • As Richard said, you forgot to "update" plot1 as the result of adding labels to the original plot.

    Here:

    plot1 <- ggplot(data1, aes(x=rel_pred,y=rel_resid)) + 
    geom_point() + 
    geom_hline(yintercept=0, colour='red') #so far so good, everything works
    
    plot1 + labs(y="Residuals", x="Fitted Values SF-12 MCS", caption="Figure  
    1. Residuals vs. fitted Values Model 1") #when I run this, it perfectly 
    adds labels
    

    Try instead

    plot1 <- ggplot(data1, aes(x=rel_pred,y=rel_resid)) + 
    geom_point() + 
    geom_hline(yintercept=0, colour='red') #so far so good, everything works
    
    plot1 <-  plot1 + labs(y="Residuals", x="Fitted Values SF-12 MCS", caption="Figure  
    1. Residuals vs. fitted Values Model 1") # no output now, it will save the result as plot1
    

    and then

    plot1 + theme(panel.background = element_rect(fill='transparent'),
    plot.background = element_rect(fill='transparent'),
    panel.border = element_blank(),
    axis.line = element_line(colour="black", size=1),
    axis.title.x = element_text(colour='black',size=6),
    axis.title.y = element_text(colour='black', size=6),
    plot.caption = element_text('Figure 1. Residuals vs. fitted Values Model   
    1')
    )
    

    will work as expected