繁体   English   中英

从ggplot2图形删除右边框

[英]Removing right border from ggplot2 graph

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

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

p + theme_classic()

主题系统妨碍了您的前进,但是您只要稍加改动就可以破解主题元素,

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()添加一个边框:

p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p + theme_classic() + annotate(
    geom = 'segment',
    y = Inf,
    yend = Inf,
    x = -Inf,
    xend = Inf
)

产生的图像

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


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

例如(对于默认主题):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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