【发布时间】:2016-03-11 22:13:22
【问题描述】:
我在使用来自Rscript 的grid.edit() 时遇到问题。我正在使用grid.edit() 来增加图例和图表中空心点的厚度。我从这篇文章 (Change thickness of a marker in ggplot2) 中获取了这个。只是看起来更好海事组织。我知道从源文件和 Rscripts 中,您可以使用 print(p) 获取要绘制的 ggplot 对象,但我需要使用 grid.edit(),所以我不知道如何解决这个问题。下面的工作示例。
我的 R 脚本名为 test.r
library(ggplot2)
library(grid)
library(gtable)
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(shape = factor(cyl))) + scale_shape(solid = FALSE)
lwd = 2 # Set line width
g = ggplotGrob(p); dev.off() # Get the plot grob
# Get the indices for the legend: t = top, r = right, ...
indices <- c(subset(g$layout, name == "guide-box", select = t:r))
# Get the row number of the legend in the layout
rn <- which(g$layout$name == "guide-box")
# Extract the legend
legend <- g$grobs[[rn]]
# Get the legend keys
pointGrobs = which(grepl("points", legend$grobs[[1]]$grobs))
# Check them out - no line width set
# for (i in pointGrobs) str(legend$grobs[[1]]$grobs[[i]])
# Set line width
for (n in pointGrobs) legend$grobs[[1]]$grobs[[n]]$gp$lwd = lwd
# Check them out - line width set
# for (i in pointGrobs) str(legend$grobs[[1]]$grobs[[i]])
# Put the modified legend back into the plot grob
g$layout$clip[g$layout$name == "panel"] <- "off"
g = gtable_add_grob(g, legend, t=indices$t, l=indices$l)
###g$grobs[[4]]$children[[2]]$gp$lwd = gpar(lwd = lwd) # Alternative for setting lwd for points in the plot
grid.newpage()
grid.draw(g)
grid.edit("geom_point.points", grep = TRUE, gp = gpar(lwd = lwd))
dev.print(cairo_pdf,filename="Aplot.pdf",
width=11,
height=8.5)
我的批处理文件。
...\R-3.2.3\bin\x64\Rscript.exe test.r
PAUSE
脚本运行,但出现以下错误。
Error in editDLfromGPath(gPath,specs,strict,grep,global,redraw):
'gPath' (geom_point.points) not found
Calls: grid.edit -> editDLfromGPath
Execution halted
另外一个 PDF 被打印到我的名为 Rplots 的工作目录中。该图是默认大小,有趣的是图例中的点很粗,但图中的点不是。似乎脚本在grid.edit() 处失败,但grid.draw() 成功。
【问题讨论】:
-
我已经构建了一个 Rscript 来批处理数据并生成一组图表。我想把它分发给我办公室里不知道 R 的其他人。任何连接到网络驱动器的人都可以从他们的本地计算机运行脚本,并且脚本将处理批处理文件目录中的文件。我可以使用 Rterm 并创建一个 Rprofile 直接运行命令或在 R 会话开始时使用
source()以获得相同的结果,还是使用source()会遇到相同的问题? -
试试这个:在
grid.edit(....行之前添加grid.force()。grid.force()使网格对网格的编辑功能可见。没有grid.force(),编辑功能只能看到一个grob。 -
它摆脱了错误但输出相同。似乎 grid.edit 没有做它的工作。谢谢,知道有用。我想我可以尝试构建一个闪亮的应用程序。
-
它对我有用。我正在使用 ggplot2 v2.1.0 和 gtable v0.2.0。
-
我会发布答案。