Setting panel.border in ggplot theme turns panel background white (wipes out the plot itself)

Joseph Kreke picture Joseph Kreke · Mar 3, 2014 · Viewed 8.4k times · Source

I would like to make the border of my plots a certain color other than black. I notice that if I set the default theme to theme_bw() using:

theme_set(theme_bw())

that I can set the border to the color I want using

theme(panel.border = element_rect(color="darkred", size=0.5, linetype="solid").

That seems to work ok. The border of each panel, whether it's a faceted plot or a single plot, takes on the "darkred" color and the rest of the plot is the same as it was before I changed the panel.border.

However, if I use a different default theme, say theme_gray() or theme_classic(), then the border changes but the contents of each of the facets is wiped out (completely white).

Any idea what is causing this difference in behavior or what I can do to fix it? I would like to use theme_gray() and put a thin colored line around the border of each facet.

Answer

Didzis Elferts picture Didzis Elferts · Mar 3, 2014

Help page of the theme() says that panel.borded= This should be used with fill=NA because it covers panels.

For the theme_bw() there is already panel.border = element_rect(fill = NA,colour = "grey50"), so when you use your statement only color changes and fill remains as NA.

For theme_grey() and theme_bw() there is panel.border = element_blank() so when you add your statement, color= and fill= are changed because previously this element was blank and default value for rect is fill="white" (at least for theme_grey()).

Use

+ theme(panel.border = element_rect(fill=NA,color="darkred", size=0.5, 
                                    linetype="solid"))