Removing right border from ggplot2 graph

2020-03-30 03:11发布

With the following code I can remove top and right borders along with other things. I wonder how to remove the right border of the ggplot2 graph only.

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

p + theme_classic()

2条回答
欢心
2楼-- · 2020-03-30 03:57

the theme system gets in the way, but with a little twist you can hack the theme elements,

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())
查看更多
Rolldiameter
3楼-- · 2020-03-30 04:01

You can just remove both borders (as it's in the first place with theme_classic()), and then add one with annotate():

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

(The idea is from: How to add line at top panel border of ggplot2)


By the way, you of course don't need to use theme_classic(). If you use a theme that has different default borders, you can switch them on/off with the theme() function's parameters panel.border (sets all borders) and axis.line (sets separate axis "borders").

For example (for default theme):

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

查看更多
登录 后发表回答