使用 ggsave 和其他保存函数绘图时出错

ton*_*13s 7 r ggplot2 sjplot ggsave

我有一个关于 ggsave() 函数的问题,我将非常感谢任何帮助和/或建议/解决方案。我正在创建四个图并将它们全部放在一个大图中,因为我想使用数据框中的所有列循环整个函数,所以我想将创建的图保存在指定的文件夹中(最好使用标识名称)。

\n
    plotting_fun3 <- function(Q){\n  \n  plot1 <- plot_likert(\n    t(Q),\n    title = "Total population",\n    legend.labels = c("strongly disagree","disagree", "neither nor", "agree", "strongly agree"),\n    grid.range = c(1.6, 1.1),\n    expand.grid = FALSE,\n    axis.labels = c(" "),\n    values = "sum.outside",\n    show.prc.sign = TRUE,\n    catcount = 4,\n    cat.neutral = 3,\n    \n  )\n  \n  plot2 <- plot_likert(\n    t(Q[survey$animal=="Dogs"]),\n    title = "Female",\n    legend.labels = c("strongly disagree","disagree", "neither nor", "agree", "strongly agree"),\n    grid.range = c(1.6, 1.1),\n    expand.grid = FALSE,\n    axis.labels = c(" "),\n    values = "sum.outside",\n    show.prc.sign = TRUE,\n    catcount = 4,\n    cat.neutral = 3,\n    \n  )\n  \n  plot3 <- plot_likert(\n    t(Q[survey$animal=="Cats"]),\n    title = "Male",\n    legend.labels = c("strongly disagree","disagree", "neither nor", "agree", "strongly agree"),\n    grid.range = c(1.6, 1.1),\n    expand.grid = FALSE,\n    axis.labels = c(" "),\n    values = "sum.outside",\n    show.prc.sign = TRUE,\n    catcount = 4,\n    cat.neutral = 3,\n    \n  )\n  \n  plot4 <- plot_likert(\n    t(Q[survey$animal=="Turtle"]),\n    title = "Others",\n    legend.labels = c("strongly disagree","disagree", "neither nor", "agree", "strongly agree"),\n    grid.range = c(1.6, 1.1),\n    expand.grid = FALSE,\n    axis.labels = c(" "),\n    values = "sum.outside",\n    show.prc.sign = TRUE,\n    catcount = 4,\n    cat.neutral = 3,\n    \n  )\n  \n  theplot <- ggarrange(plot1, plot2, plot3, plot4, \n                       labels = NULL,\n                       common.legend = TRUE,\n                       legend = "bottom",\n                       ncol = 1, nrow = 4)\n  \n  #ggsave(filename=paste(Q,".png",sep=""), plot=theplot, device = "png")\n  \n  #ggsave(filename=paste("animal_plot", ID, ".jpeg"), plot=plots[[x]])\n  \n  #ggsave(path = "/myDirectory",\n  #       device = "png", filename = "animal_plot", plot = theplot)\n  \n  #save_plot(filename = "hello", plot = theplot, \n  #          "/myDirectory",\n  #          device = "png")\n\n  #ggsave(sprintf("%s.pdf", Q), device = "pdf")\n  \n  return(theplot)\n}\n
Run Code Online (Sandbox Code Playgroud)\n

注释行显示了我尝试将绘图保存在目录中的各种方法。我遇到两个不同的问题:

\n

要么:我在堆栈溢出上找到的大多数 ggsave 建议。其中有几个不包括该行device = "png"。如果我省略这行代码,我总是会得到这样的结果:

\n
 Fehler: `device` must be NULL, a string or a function.\nRun `rlang::last_error()` to see where the error occurred. \n
Run Code Online (Sandbox Code Playgroud)\n

如果我遵循该命令,我会得到:

\n
<error/rlang_error>\n`device` must be NULL, a string or a function.\nBacktrace:\n 1. global::plotting_fun3(survey[, 9])\n 2. ggplot2::ggsave(sprintf("%s.pdf", Q))\n 3. ggplot2:::plot_dev(device, filename, dpi = dpi)\nRun `rlang::last_trace()` to see the full context.\n> rlang::last_trace()\n<error/rlang_error>\n`device` must be NULL, a string or a function.\nBacktrace:\n    \xe2\x96\x88\n 1. \xe2\x94\x94\xe2\x94\x80global::plotting_fun3(survey[, 9])\n 2.   \xe2\x94\x94\xe2\x94\x80ggplot2::ggsave(sprintf("%s.pdf", Q))\n 3.     \xe2\x94\x94\xe2\x94\x80ggplot2:::plot_dev(device, filename, dpi = dpi)\n
Run Code Online (Sandbox Code Playgroud)\n

所以在网上我发现有人有相同或相似的问题,建议一直是使用device = "png"或类似。

\n

现在,如果我这样做,我会遇到一个不同的问题:\n绘图保存在正确的目录中,但名称错误。通常名称是“3.png”或“3.pdf”或取决于我创建的内容。如果“3.png”已经存在,它会为文件提供另一个编号。

\n

三个月前,我在一个旧项目中遇到了这个问题,无法解决,现在又遇到了。

\n

就其价值而言,我使用 macOS Mojave 10.14.6,我的 R 版本是版本 1.3.1093

\n

预先感谢您的任何想法、建议或其他意见。

\n

[编辑]

\n

这是一些示例数据:

\n
 > str(myDF[,c(2,9:10)])\n data.frame':   123 obs. of  3 variables:\n $ animal: chr  "Cats" "Cats" "Turtles" "Cats" ...\n $ q8    : int  3 5 5 3 4 4 2 5 3 5 ...\n $ q9.1  : int  4 5 5 4 3 4 2 4 2 4 ...\n
Run Code Online (Sandbox Code Playgroud)\n

所有观测值的值都保持在 1 到 5 之间。它们实际上代表了诸如“强烈同意”、“同意”、“既不同意也不不同意”等答案。

\n

或者,如果您更喜欢这个而不是另一个:

\n
> myDF[,c(2,9:10)]\n     animal q8 q9.1\n1      Cats  3    4\n2      Cats  5    5\n3   Turtles  5    5\n4      Cats  3    4\n5   Turtles  4    3\n6   Turtles  4    4\n7   Turtles  2    2\n8      Cats  5    4\n9      Cats  3    2\n10  Turtles  5    4\n11  Turtles  4    3\n12  Turtles  3    3\n13     Dogs  3    3\n14     Cats  3    3\n15     Dogs  1    1\n16     Dogs  1    3\n
Run Code Online (Sandbox Code Playgroud)\n

Sin*_*yen 5

文件名的问题是由于您Q在文件名定义中使用了数据帧,因此它将导致一些非常混乱的方式,具体取决于您的系统处理文件名的方式。

# This command result in a few long character depend on number of columns in Q.
# 4 columns w+ill result 4 long character and ggsvave will return the error
# Error: `device` must be NULL, a string or a function.
ggsave(filename=paste(Q,".png",sep=""), plot=theplot, device = "png")
  
# Again not sure what ID is here but if it was a dataframe you got
# same error with previous one.
ggsave(filename=paste("animal_plot", ID, ".jpeg"), plot=plots[[x]])

# This one it doesn't specific a file name but a directory
# ggsave will return an error:
# Error: Unknown graphics device ''
# If you specify device = "png" - error will be:
# Error in grid.newpage() : could not open file '/home/sinh' 
ggsave(path = "/myDirectory",
       device = "png", filename = "animal_plot", plot = theplot)

# Why there is a param "/myDirectory" here? and you should specify the extention
# in the file name. So the correct param is:
# filename = "/myDirectory/hello.png"
save_plot(filename = "hello", plot = theplot, 
          "/myDirectory",
          device = "png")
Run Code Online (Sandbox Code Playgroud)

这是应该可以正常工作的一个,但您需要手动输入文件名:

character_variable <- "my_character_variable_here_"
index_number <- 20
# If you specify sep = "" then just need to use paste0
file_name <- paste0(character_variable, index_number)
ggsave(filename=paste(file_name, ".jpeg"), plot=plots[[x]], device = "png")
Run Code Online (Sandbox Code Playgroud)

这是我根据你的函数重写的函数。你可以尝试一下并稍微调整一下

# df is your survey data.frame
# q_column_name is the name of questionare column that you want to graph.
# the final output file will use q_column_name as file name.
plotting_fun3 <- function(df, q_column_name){
  
  require(foreach)
  require(dplyr)
  require(tidyr)
  
  graph_data <- df %>% select(one_of("animal", q_column_name))
  
  plot1 <- plot_likert(
    t(graph_data),
    title = "Total population",
    legend.labels = c("strongly disagree","disagree", "neither nor", "agree", "strongly agree"),
    grid.range = c(1.6, 1.1),
    expand.grid = FALSE,
    axis.labels = c(" "),
    values = "sum.outside",
    show.prc.sign = TRUE,
    catcount = 4,
    cat.neutral = 3,
  )
  
  animal_plots <- foreach(current_animal = c("Dog", "Cats", "Turtle")) %do% {
    plot_likert(
      t(graph_data %>% filter(animal == current_animal)),
      title = "Female",
      legend.labels = c("strongly disagree","disagree", "neither nor", "agree", "strongly agree"),
      grid.range = c(1.6, 1.1),
      expand.grid = FALSE,
      axis.labels = c(" "),
      values = "sum.outside",
      show.prc.sign = TRUE,
      catcount = 4,
      cat.neutral = 3
    )
  }
  
  theplot <- ggarrange(plot1, animal_plots[[1]],
                       animal_plots[[2]], animal_plots[[3]], 
                       labels = NULL,
                       common.legend = TRUE,
                       legend = "bottom",
                       ncol = 1, nrow = 4)
  
  ggsave(filename=paste(q_column_name, ".png",sep=""), plot=theplot, device = "png")
  
  return(theplot)
}

Run Code Online (Sandbox Code Playgroud)

以下是该功能的使用方法

# Assume that your survey dataframe variable is myDF
my_new_plot <- plotting_fun3(df = myDF, q_column_name = "q8")
Run Code Online (Sandbox Code Playgroud)

[更新] - 添加了解决图表问题的功能。