关于r:从ggplot2图中删除右边框

Removing right border from ggplot2 graph

通过以下代码,我可以删除顶部和右侧边框以及其他内容。 我想知道如何仅删除ggplot2图的右边界。

1
2
3
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()

p + theme_classic()


主题系统遇到了麻烦,但是您可以稍作改动就可以破解主题元素,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
library(ggplot2)
library(grid)
element_grob.element_custom <- function(element, ...)  {

  segmentsGrob(c(1,0,0),
               c(0,0,1),
               c(0,0,1),
               c(0,1,1), gp=gpar(lwd=2))
}
## silly wrapper to fool ggplot2
border_custom <- function(...){
  structure(
    list(...), # this ... information is not used, btw
    class = c("element_custom","element_blank","element") # inheritance test workaround
  )

}
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() +
  theme_classic() +
  theme(panel.border=border_custom())


您可以只删除两个边框(使用theme_classic()首先将其删除),然后使用annotate()添加一个边框:

1
2
3
4
5
6
7
8
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p + theme_classic() + annotate(
    geom = 'segment',
    y = Inf,
    yend = Inf,
    x = -Inf,
    xend = Inf
)

the resulting image

(想法来自:如何在ggplot2的顶部面板边框处添加行)

顺便说一句,您当然不需要使用theme_classic()。 如果使用具有不同默认边框的主题,则可以使用theme()函数的参数panel.border(设置所有边框)和axis.line(设置单独的轴"边框")打开/关闭它们。

例如(对于默认主题):

1
2
3
4
5
6
7
8
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p + annotate(
    geom = 'segment',
    y = Inf,
    yend = Inf,
    x = -Inf,
    xend = Inf
) + theme(panel.border = element_blank(), axis.line = element_line())

the resulting image 2