【问题标题】:Removing right border from ggplot2 graph从ggplot2图中删除右边框
【发布时间】:2019-07-17 03:55:41
【问题描述】:

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

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

p + theme_classic()

【问题讨论】:

  • 这并不容易,因为panel.border是作为element_rect对象管理的,所以它已经是一个矩形了。
  • 我同意 Davide 的观点:这可能并不容易。我假设 theme_classic 实际上完全移除了盒子,而是绘制了轴线。为了说明这一点,请尝试p+theme(axis.line=element_line())。它将使用标准主题绘制p,但添加了轴线。
  • @lawyeR:不,这不是stackoverflow.com/q/10861773/707145的重复。

标签: r plot ggplot2 r-grid


【解决方案1】:

主题系统会妨碍您,但稍加改动就可以破解主题元素,

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

【讨论】:

  • 感谢您的精彩回答。如果您不介意,请查看我的编辑并提出任何解决方案。再次感谢您的帮助。
  • 大概,如果您在将绘图转换为 gtable 之前将此主题应用于绘图,则应传递此元素
【解决方案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
)

(想法来自:How to add line at top panel border of 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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 1970-01-01
    相关资源
    最近更新 更多