【问题标题】:Adding grid lines to a ggplot with a background image将网格线添加到带有背景图像的 ggplot
【发布时间】:2020-05-25 19:30:39
【问题描述】:

我使用 ggplot2 制作了一个绘图并使用图形作为背景。现在我想添加网格以使其更清晰,但我被卡住了。我的 ggplot2 函数:

library(ggplot2)
library(ggpubr)

ggplot(df), aes(x = Year, y = Number)) +
  background_image(jpg) +
  geom_line(color = "black", size = 2) +
  labs(title = "Title", y = "Name1", x = "Name2")

如果有任何帮助,我将不胜感激。

【问题讨论】:

  • 我试过主题和网格功能,但我看不到任何网格线

标签: r ggplot2 gridlines ggpubr


【解决方案1】:

使用ggpubr::background_image 中的示例,这可以通过设置panel.background = element_blank()panel.ontop = TRUE 来实现。试试这个:

library(ggpubr)
#> Loading required package: ggplot2
library(ggplot2)

img.file <- system.file(file.path("images", "background-image.png"),
                        package = "ggpubr")
img <- png::readPNG(img.file)

# Plot with background image
ggplot(iris, aes(Species, Sepal.Length))+
  background_image(img)+
  geom_boxplot(aes(fill = Species), color = "white")+
  theme(panel.background = element_blank(),
        panel.ontop = TRUE)

reprex package (v0.3.0) 于 2020-05-25 创建

编辑:另一种方法是使用geom_vlinegeom_hline 手动绘制网格线:

library(ggpubr)
#> Loading required package: ggplot2
library(ggplot2)

img.file <- system.file(file.path("images", "background-image.png"),
                        package = "ggpubr")
img <- png::readPNG(img.file)

# Plot with background image
ggplot(iris, aes(Species, Sepal.Length))+
  background_image(img) +
  geom_vline(aes(xintercept = Species), color = "white") +
  geom_hline(yintercept = c(5, 6, 7, 8), color = "white") +
  geom_boxplot(aes(fill = Species), color = "white")

reprex package (v0.3.0) 于 2020 年 5 月 26 日创建

【讨论】:

  • 非常感谢它完美运行。有什么选项可以让这个 geom_boxplot 放在一切之上?现在它在网格线的“后面”,它并不是我想要的。
  • 嗨@Aleksandra。我刚刚做了一个编辑。实现您想要的另一种方法是使用geom_vlinegeom_hline 手动绘制网格线。这样箱线图将绘制在网格线的顶部。
猜你喜欢
  • 1970-01-01
  • 2012-07-03
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
  • 1970-01-01
  • 2015-11-06
  • 2012-04-09
  • 2011-06-01
相关资源
最近更新 更多