简体   繁体   English

从 ggplot2 中删除网格、背景颜色和顶部和右侧边框

[英]Remove grid, background color, and top and right borders from ggplot2

I would like to reproduce the plot immediately below by using ggplot2. I can come close, but cannot remove the top and right borders.我想通过使用 ggplot2 重现下面的 plot。我可以靠近,但不能删除顶部和右侧边框。 Below I present several attempts using ggplot2, including several suggestions found on or via Stackoverflow.下面我展示了使用 ggplot2 的几次尝试,包括在 Stackoverflow 上或通过 Stackoverflow 找到的一些建议。 Unfortunately I have not been able to get those suggestions to work.不幸的是,我无法让这些建议发挥作用。

I am hoping someone may be able to correct one or more of the code snippets below.我希望有人能够更正下面的一个或多个代码片段。

Thank you for any suggestions.谢谢你的任何建议。

# desired plot
a <- seq(1,20)
b <- a^0.25
plot(a,b, bty = "l")


library(ggplot2)

df <- as.data.frame(cbind(a,b))

# 1. ggplot2 default
ggplot(df, aes(x = a, y = b)) + geom_point()

# 2. removes background color
ggplot(df, aes(x = a, y = b)) + geom_point() + opts(panel.background = theme_rect(fill='white', colour='black'))

# 3. also removes gridlines
none <- theme_blank()
ggplot(df, aes(x = a, y = b)) + geom_point() + opts(panel.background = theme_rect(fill='white', colour='black')) + opts(panel.grid.major = none, panel.grid.minor = none)

# 4. does not remove top and right border
ggplot(df, aes(x = a, y = b)) + geom_point() + opts(panel.background = theme_rect(fill='white', colour='black')) + opts(panel.grid.major = none, panel.grid.minor = none) + opts(panel.border = none)

# 5. does not remove top and right border
ggplot(df, aes(x = a, y = b)) + geom_point() + opts(panel.background = theme_rect(fill='white', colour='black')) + opts(panel.grid.major = none, panel.grid.minor = none) + opts(axis.line = theme_segment())

# 6. removes x and y axis in addition to top and right border
# http://stackoverflow.com/questions/5458409/remove-top-and-right-border-from-ggplot2
ggplot(df, aes(x = a, y = b)) + geom_point() + opts(panel.background = theme_rect(fill='white', colour='black')) + opts(panel.grid.major = none, panel.grid.minor = none) + opts(panel.background=theme_rect(colour=NA))

# 7. returns error when attempting to remove top and right border
# https://groups.google.com/group/ggplot2/browse_thread/thread/f998d113638bf251
#
# Error in el(...) : could not find function "polylineGrob"
#
theme_L_border <- function(colour = "black", size = 1, linetype = 1) { 
   structure( 
     function(x = 0, y = 0, width = 1, height = 1, ...) { 
       polylineGrob( 
         x=c(x+width, x, x), y=c(y,y,y+height), ..., default.units = "npc", 
         gp=gpar(lwd=size, col=colour, lty=linetype), 
       ) 
     }, 
     class = "theme", 
     type = "box", 
     call = match.call() 
   )
}

ggplot(df, aes(x = a, y = b)) + geom_point() + opts(panel.background = theme_rect(fill='white', colour='black')) + opts(panel.grid.major = none, panel.grid.minor = none) + opts( panel.border = theme_L_border())

EDIT Ignore this answer.编辑忽略这个答案。 There are now better answers.现在有更好的答案。 See the comments.看评论。 Use + theme_classic()使用+ theme_classic()

EDIT编辑

This is a better version.这是一个更好的版本。 The bug mentioned below in the original post remains (I think).原始帖子中下面提到的错误仍然存​​在(我认为)。 But the axis line is drawn under the panel.但是轴线是在面板下方绘制的。 Therefore, remove both the panel.border and panel.background to see the axis lines.因此,删除panel.borderpanel.background以查看轴线。

library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))

ggplot(df, aes(x = a, y = b)) + geom_point() +
  theme_bw() +
  theme(axis.line = element_line(colour = "black"),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank(),
    panel.background = element_blank()) 

在此处输入图片说明

Original post This gets close.原帖这就接近了。 There was a bug with axis.line not working on the y-axis ( see here ), that appears not to be fixed yet.有一个axis.line不能在 y 轴上工作的错误( 请参阅此处),该错误似乎尚未修复。 Therefore, after removing the panel border, the y-axis has to be drawn in separately using geom_vline .因此,移除面板边框后,必须使用geom_vline单独绘制 y 轴。

library(ggplot2)
library(grid)

a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))

p = ggplot(df, aes(x = a, y = b)) + geom_point() +
   scale_y_continuous(expand = c(0,0)) +
   scale_x_continuous(expand = c(0,0)) +
   theme_bw() +
   opts(axis.line = theme_segment(colour = "black"),
        panel.grid.major = theme_blank(),
        panel.grid.minor = theme_blank(),
        panel.border = theme_blank()) +
    geom_vline(xintercept = 0)
p

The extreme points are clipped, but the clipping can be undone using code by baptiste .极值点被剪裁,但剪裁可以使用baptiste 的代码撤销。

gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)

在此处输入图片说明

Or use limits to move the boundaries of the panel.或者使用limits来移动面板的边界。

ggplot(df, aes(x = a, y = b)) + geom_point() +
   xlim(0,22) +  ylim(.95, 2.1) +
   scale_x_continuous(expand = c(0,0), limits = c(0,22)) +
   scale_y_continuous(expand = c(0,0), limits = c(.95, 2.2)) +   
   theme_bw() +
   opts(axis.line = theme_segment(colour = "black"),
        panel.grid.major = theme_blank(),
        panel.grid.minor = theme_blank(),
        panel.border = theme_blank()) +
    geom_vline(xintercept = 0)

Recent updates to ggplot (0.9.2+) have overhauled the syntax for themes.最近对 ggplot (0.9.2+) 的更新彻底修改了主题的语法。 Most notably, opts() is now deprecated, having been replaced by theme() .最值得注意的是, opts()现在已被弃用,已被替换为theme() Sandy's answer will still (as of Jan '12) generates a chart, but causes R to throw a bunch of warnings.桑迪的回答仍然会(截至 12 年 1 月)生成一个图表,但会导致 R 抛出一堆警告。

Here's updated code reflecting current ggplot syntax:这是反映当前 ggplot 语法的更新代码:

library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))

#base ggplot object
p <- ggplot(df, aes(x = a, y = b))

p +
  #plots the points
  geom_point() +

  #theme with white background
  theme_bw() +

  #eliminates background, gridlines, and chart border
  theme(
    plot.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank()
  ) +

  #draws x and y axis line
  theme(axis.line = element_line(color = 'black'))

generates:产生:

绘图输出

An alternative to theme_classic() is the theme that comes with the cowplot package, theme_cowplot() (loaded automatically with the package). theme_classic()的替代方案是cowplot包随附的主题, theme_cowplot() (随包自动加载)。 It looks similar to theme_classic() , with a few subtle differences.它看起来类似于theme_classic() ,但有一些细微的差别。 Most importantly, the default label sizes are larger, so the resulting figures can be used in publications without further modifications needed (in particular if you save them with save_plot() instead of ggsave() ).最重要的是,默认标签尺寸更大,因此生成的数字可以在不需要进一步修改的情况下用于出版物(特别是如果您使用save_plot()而不是ggsave()保存它们)。 Also, the background is transparent, not white, which may be useful if you want to edit the figure in illustrator.此外,背景是透明的,而不是白色,如果您想在 illustrator 中编辑图形,这可能很有用。 Finally, faceted plots look better, in my opinion.最后,在我看来,分面图看起来更好。

Example:例子:

library(cowplot)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))

p <- ggplot(df, aes(x = a, y = b)) + geom_point()
save_plot('plot.png', p) # alternative to ggsave, with default settings that work well with the theme

This is what the file plot.png produced by this code looks like:这是这段代码生成的文件plot.png样子:在此处输入图片说明

Disclaimer: I'm the package author.免责声明:我是包的作者。

I followed Andrew's answer , but I also had to follow https://stackoverflow.com/a/35833548 and set the x and y axes separately due to a bug in my version of ggplot (v2.1.0).我遵循了安德鲁的回答,但由于我的 ggplot (v2.1.0) 版本中的错误,我也不得不遵循https://stackoverflow.com/a/35833548并分别设置 x 和 y 轴。

Instead of代替

theme(axis.line = element_line(color = 'black'))

I used我用了

theme(axis.line.x = element_line(color="black", size = 2),
    axis.line.y = element_line(color="black", size = 2))

The above options do not work for maps created with sf and geom_sf() .上述选项不适用于使用sfgeom_sf()创建的地图。 Hence, I want to add the relevant ndiscr parameter here.因此,我想在这里添加相关的ndiscr参数。 This will create a nice clean map showing only the features.这将创建一个漂亮的干净地图,仅显示特征。

library(sf)
library(ggplot2)

ggplot() + 
  geom_sf(data = some_shp) + 
  theme_minimal() +                     # white background
  theme(axis.text = element_blank(),    # remove geographic coordinates
        axis.ticks = element_blank()) + # remove ticks
  coord_sf(ndiscr = 0)                  # remove grid in the background

Simplification from the above Andrew's answer leads to this key theme to generate the half border.从上面安德鲁的回答中简化导致这个关键主题生成半边。

theme (panel.border = element_blank(),
       axis.line    = element_line(color='black'))

Here's an extremely simple answer这是一个非常简单的答案

yourPlot +
  theme(
    panel.border = element_blank(), 
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(), 
    axis.line = element_line(colour = "black")
    )

It's that easy.就这么简单。 Source: the end of this article来源:结束文章

You may be check also panel.background as well.您也可以检查panel.background

 theme(
        panel.background = element_rect(fill = "black"),
        panel.grid.major = element_blank(), panel.grid.minor = element_blank()

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

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