【问题标题】:return plot and values from a function together [duplicate]一起从函数返回绘图和值
【发布时间】:2017-12-05 03:52:51
【问题描述】:

我有这样的功能:

fun <- function(dataset){
  require(ggplot2)
  g <- ggplot(dataset, aes(x = x, y = y)) + geom_smooth(method = "lm") + geom_point()

l<-lm(y~x)
return (list(l, g))
    }

我想返回绘图和值,但它不返回绘图并且我遇到了这个错误:

.Call.graphics(C_palette2, .Call(C_palette2, NULL)) 中的错误:
无效的图形状态

我能做什么?

【问题讨论】:

  • 请先提供Minimal Complete and Verifiable Example。没有它,很难找出问题所在。我确实在 return 语句中看到了一个错字(g 而不是p),但这不应该是主要问题,我认为。
  • 你想让这些值出现在图上吗?
  • 会好很多,但我的问题是关于在控制台中打印值

标签: r function plot ggplot2 lm


【解决方案1】:

以下作品,你可以得到情节。但是,R 警告说这不是这样做的方法。

fun <- function(dataset){
  require(ggplot2)
  p <- ggplot(dataset, aes(x = x, y = y)) + 
       geom_smooth(method = "lm") + geom_point()

  l <- lm(y~x, data=dataset)
  return (list(l, p))
}

dataset <- data.frame(x= 1:10, y=1:10)
out <- fun(dataset)

编辑:我看过警告,似乎可以忽略。见链接https://stat.ethz.ch/pipermail/r-devel/2016-December/073554.html

【讨论】:

  • 我试过了,它返回这个 [[1]] 调用:lm(formula = df[, 2] ~ df[, 1]) Coefficients: (Intercept) df[, 1] 3.898e- 16 -7.059e-01 [[2]] .Call.graphics (C_palette2, .Call(C_palette2, NULL)) 中的错误:无效的图形状态
  • 剧情不是我画的
  • 要获取绘图,您需要在命令提示符下键入out$p。该函数仅返回绘图。
  • 我已经测试了我给出的代码。有用。所以,似乎还有别的问题。
  • 不,不幸的是没有。它为 out$p 粘贴了 NULL
猜你喜欢
  • 2022-10-14
  • 1970-01-01
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
  • 2014-06-23
  • 2022-11-25
相关资源
最近更新 更多