rggplot2ggsave

Encounter "Error: $ operator is invalid for atomic vectors" when using ggsave


Here's the code I prepare as an example. Everything was fine until I ran the ggsave. The error is about $ operator, which is quite confusing. I have seen many people who have similar error messages in different cases. Is it my fault or an internal R error?

library(tidyverse)

xx <- seq(0,2,0.01); yy <- seq(0,2,0.02); zz <- seq(0,2,0.04)

dat <- data.frame(
  times = c(xx, yy, zz),
  val = c(sin(xx), sin(yy)+rnorm(length(yy),sd=0.2), sin(zz)+rnorm(length(zz),sd=0.3)),
  method = c(rep("A", length(xx)), rep("B", length(yy)), rep("C", length(zz)))
)

fig <- ggplot(dat) +
  geom_line(aes(x = times, y = val, col = method, linetype = method)) + 
  theme_minimal() +
  scale_color_manual(values = c("#29BDCE", "#ED8534", "#625559")) +
  scale_linetype_manual(values=c("solid", "longdash", "dashed")) +
  theme(legend.title = element_blank(),
        legend.position = "none") 

ggsave(fig, "D:/ResearchesAndProjects/2021_2_ODEadditive/code-ode-additive/examples/plots/test.png",
       device = "png", type ="cairo")
#> Saving 7 x 5 in image
#> Error: $ operator is invalid for atomic vectors
Created on 2021-07-01 by the reprex package (v2.0.0)

Solution

  • from ?ggsave the first argument is the file name whereas the second argument is the plot. Try -

    ggsave("D:/ResearchesAndProjects/2021_2_ODEadditive/code-ode-additive/examples/plots/test.png",
           fig, device = "png", type ="cairo")