ggplot 的 qplot 在采购时不执行

发布于 2025-01-10 04:50:00 字数 413 浏览 2 评论 0原文

假设我有 2 个源文件,第一个名为 example1.r,第二个名为 example2.r(如下所示)。

example1.r

plot(1:10,1:10)

example2.r

qplot(1:10,1:10)

当我获取 example1.r 时,会绘制图表。但是,当我获取 example2.r 时,情况并非如此。这里的解决方案是什么?

(example2.r中的qplot是ggplot2的函数)

Let's assume I have 2 source files, the first one named example1.r and the second one example2.r (given below).

example1.r

plot(1:10,1:10)

example2.r

qplot(1:10,1:10)

When I source example1.r, the graph is drawn. It does not, however, when I source example2.r. What is the solution here?

(qplot in example2.r is ggplot2's function)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

假装爱人 2025-01-17 04:50:00

更新

  • .R 文件: source 的选项 print.eval=TRUE 将导致打印行为评估结果就像交互式命令行中一样。

source("Script.R", print.eval=TRUE)

  • .Rnw 文件: knitr 默认情况下模拟交互式命令行的行为字。 打印。请注意,也可以将 knitr 指定为 R 包小插图的 Sweaving 引擎。

This is my original answer. But note that this workaround is IMHO completely obsolete now (and it always was good for a small lazy niche only).

这是著名的 常见问题解答7.22: 为什么点阵/网格图形不起作用?

对于像ggplot2或lattice这样的网格图形,您需要打印图形对象才能实际绘制它。

在命令行上交互地,这是自动完成的。在其他地方(在要获取的文件、循环、函数、Sweave 块内),您需要显式地打印它。

print (qplot (1 : 10, 1 : 10))

或者,您可以重新定义 qplot 来进行打印:(

qplot <- function (x, y = NULL, z = NULL, ...) {
  p <- ggplot2::qplot (x = x, y = y, z = z, ...)
  print (p)
}

这会将轴标签更改为 x 和 y)。

我在小插图中使用这种方法,我想编写与交互式会话中的用户键入代码完全相同的代码。

Update:

  • .R files: source's option print.eval=TRUE will lead to printing behaviour of the evaluation result like in the interactive command line.

source("Script.R", print.eval=TRUE)

  • .Rnw files: knitr by default emulates the behaviour of the interactive command line wrt. printing. Note that knitr can be specified as Sweaving engine also for R package vignettes.


This is my original answer. But note that this workaround is IMHO completely obsolete now (and it always was good for a small lazy niche only).

This is the famous FAQ 7.22: Why do lattice/trellis graphics not work?.

For grid graphics like ggplot2 or lattice, you need to print the graphics object in order to actually draw it.

Interactively on the command line this is done automatically. Everywhere else (inside files to be sourced, loops, functions, Sweave chunks) you need to print it explicitly.

print (qplot (1 : 10, 1 : 10))

Alternatively, you can redefine qplot to do the printing:

qplot <- function (x, y = NULL, z = NULL, ...) {
  p <- ggplot2::qplot (x = x, y = y, z = z, ...)
  print (p)
}

(this changes the axis labels to x and y).

I use this approach in vignettes where I want to write code exactly as a user in an interactive session would type it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文