在R的ggplot2的geom_label的pdf输出中去掉边界

时间:2017-04-14 18:52:40

标签: r ggplot2

我在输出到pdf时试图摆脱geom_label创建的边框。设置lable.size = 0似乎在输出到png时或仅在R会话中的绘图窗口中有效但在输出到pdf时边界仍然存在。我喜欢geom_label over geom_text,因为背景使得当绘图上有线条时更容易阅读。由于我正在使用后者的情节,所以我更容易获得pdf输出,所以如果有人知道如何摆脱那将是伟大的边界。

我目前在Mac OS Sierra上使用ggplot 2.2.1和R 3.3.3。下面是一些示例代码。

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()

1 个答案:

答案 0 :(得分:8)

修改:我查看了ggplot2的源代码,实际上是grid问题,而不是ggplot2。由于某种原因,grid似乎会覆盖lwd。例如,运行以下代码,即使我们指定lwd = 0,我们也会看到仍有线宽。

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

您似乎需要指定lwd = NA。例如,这不会为您提供边框:grid.newpage();grid.draw(roundrectGrob(gp = gpar(lwd = NA)))

话虽如此,如果您将ggplot代码更改为:

,它应该可以正常工作(没有警告消息)
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