0
library(tidyverse)
library(ggh4x)
library(showtext)
font_add("Bookman Old Style", "BOOKOS.TTF")
showtext_auto()

df <- tibble::tibble(
  estacion = c(
    "HU22_2", "HU33_3", "HU11_1", "SV33_3", "SV11_1", "SV22_2", "QE11_1",
    "QE22_2", "QE33_3", "SJ11_1", "SJ22_2", "TI11_1", "TI22_2"
  ),
  quebrada = rep(c("yauH", "teiS", "reuQ", "\U{E9}soJ", "aniT"), rep(3:2, 3:2)),
  n = c(14L, 13L, 11L, 17L, 16L, 16L, 14L, 9L, 9L, 10L, 9L, 9L, 6L),
  etiqueta = c("14", "13", "11", "17", "16", "16", "14", "9", "9", "10", "9", "9", "6"),
)

making plot:

grafico <- df %>% 
  ggplot(aes(x = estacion, y = n)) +
  geom_col(width = 1, position = position_dodge(0.5)) +
  ggh4x::facet_nested(cols = vars(quebrada),
                      switch = "x",
                      scales = "free_x",
                      space = "free_x") +
theme(axis.line = element_blank(),
      axis.ticks = element_blank(),
      axis.text.y = element_text(angle = 0, size = 29),
      axis.title = element_text(face = "bold", size = 38),
      
      panel.background = element_blank(),
      plot.margin = margin(t = 0.8, r = 0.8, unit = "cm"),
      panel.grid.major.x = element_blank(),
      panel.grid.minor.y = element_blank(),
      panel.grid.major.y = element_line(colour = "gray"),
      legend.text = element_text(size = 30),
      text = element_text(family = "Bookman Old Style"),
      axis.text.x = element_text(angle = 0, size = 29, lineheight = unit(.8, "lines")),
      strip.background = element_rect(fill = "white"),
      strip.text = element_text(family = "Bookman Old Style",
                                                           size = 25,
                                                           lineheight = 0.6,
                                                           hjust = 0.5),
      strip.placement = "outside",
      
      panel.spacing.x = unit(0, "cm"),
      axis.title.y = ggtext::element_markdown()) +
  labs(y = "Riqueza de especies")

This plot displays and is saved correctly as a png image.

enter image description here

Then, I do a simple modification using grid in order to add vertical lines among strips.

g <- ggplotGrob(grafico)

lr2 <-  polylineGrob(x=c(0,0,1,1),
                     y=c(0,1,0,1),
                     id=c(1,1,2,2),
                     gp=gpar(col="gray", lwd=1))

for (k in grep("strip-b", g$layout$name)) {
  g$grobs[[k]]$grobs[[1]]$children[[1]] <- lr2
}

The plot displays right in the plot viewer and you see the added vertical lines in red.

enter image description here

Then I try to save this image into a png image using.

png(
  filename = "image.png",
  width = 15.5,
  height = 8,
  units = "cm",
  res = 300
)

g %>% plot()

dev.off()


The image is no saved correctly as you see below.

enter image description here

I already tried to save with ggsave but the error remains the same. The desired output is the image like we see in the viewer.

Alvaro Morales
  • 1,845
  • 3
  • 12
  • 21

0 Answers0