Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting rid of border in pdf output for geom_label for ggplot2 in R

Tags:

r

ggplot2

I'm attempting to get rid of the border created by geom_label when outputting to a pdf. Setting the lable.size = 0 seems to work when outputting to png or just in the plot window in the R sessions but when outputting to pdf the border is still there. I like the geom_label over geom_text as the background makes it easier to read when there are lines on the plot. Due to what I'm doing with the plot latter it's easier for me to have a pdf output so if anyone knows how to get rid of the border that would be great.

I'm currently using ggplot 2.2.1 and R 3.3.3 on Mac OS Sierra. Below is some example code.

require(ggplot2)
#no border
ggplot(data.frame(nums = 1:10), aes(x =nums, y = nums) ) +
  geom_point() +
  geom_label(label = "italic(R) ^ 2 == .87", label.size = 0, x = 2, y = 8, vjust = "inward", hjust = "inward", parse = T) + 
  theme_bw()


pdf("testPlot.pdf")
#border appears in pdf 
print(ggplot(data.frame(nums = 1:10), aes(x =nums, y = nums) ) +
        geom_point() +
        geom_label(label = "italic(R) ^ 2 == .87", label.size = 0, x = 2, y = 8, vjust = "inward", hjust = "inward", parse = T) + 
        theme_bw())
dev.off()


png("testPlot.png")
#no border with png
print(ggplot(data.frame(nums = 1:10), aes(x =nums, y = nums) ) +
        geom_point() +
        geom_label(label = "italic(R) ^ 2 == .87", label.size = 0, x = 2, y = 8, vjust = "inward", hjust = "inward", parse = T) + 
        theme_bw())
dev.off()
like image 685
Nick Hathaway Avatar asked Apr 14 '17 18:04

Nick Hathaway


1 Answers

Edit: I looked into the source code for ggplot2 and it's actually a grid issue and not ggplot2. It looks like grid overrides the lwd for some reason. For example running the below code we see that there is still a line width even if we specify lwd = 0.

library(grid)
grid.newpage();grid.draw(roundrectGrob(gp = gpar(lwd = 0)))

Looks like you need to specify lwd = NA. For example, this gives you no border: grid.newpage();grid.draw(roundrectGrob(gp = gpar(lwd = NA)))

That being said, it should work (without warning messages) if you change your ggplot code to:

ggplot(data.frame(nums = 1:10), aes(x =nums, y = nums) ) +
  geom_point() +
  geom_label(label = "italic(R) ^ 2 == .87", label.size = NA, x = 2, y = 8, vjust = "inward", hjust = "inward", parse = T) + 
  theme_bw()

enter image description here

like image 168
Mike H. Avatar answered Nov 09 '22 05:11

Mike H.