简体   繁体   中英

Removing right border from ggplot2 graph

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

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

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

生成的图像2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM