从ggplot2图中删除右边框

3

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

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

p + theme_classic()

这并不容易,因为panel.border被视为一个element_rect对象进行管理,因此它已经是一个矩形。 - Davide Passaretti
1
可能重复: https://dev59.com/VWgv5IYBdhLWcg3wFs2l - lawyeR
我同意Davide的观点:这可能不是很容易实现。我认为theme_classic实际上完全删除了框,并绘制了坐标轴线。为了说明这一点,请尝试使用p+theme(axis.line=element_line())。它将使用标准主题绘制p,但添加了坐标轴线。 - Stibu
@lawyeR:不,这不是stackoverflow.com/q/10861773/707145的重复。 - MYaseen208
2个回答

5
主题系统可能会妨碍操作,不过通过一些小技巧,你可以对主题元素进行修改。
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())

感谢您的好回答。请查看我的编辑并提出任何解决方案,如果您不介意的话。再次感谢您的帮助。 - MYaseen208
据推测,如果您在将图表转换为gtable之前将此主题应用于图表,则应将此元素传递。 - baptiste

2
您可以先移除两个边框(因为在第一个位置使用了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
)

the resulting image

这个想法来自于:如何在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())

the resulting image 2


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接