I'm having problems using grid.edit()
from an Rscript
. I'm using grid.edit()
to increase the thickness of hollow points in the legend and chart. I took this from this post (Change thickness of a marker in ggplot2). Just looks way better IMO. I know that from source files and Rscripts you can get ggplot
objects to plot using print(p)
, but I need to use grid.edit()
so I'm not sure how to fix this. Working example below.
My R script called 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)
My batch file.
...\R-3.2.3\bin\x64\Rscript.exe test.r
PAUSE
The script runs and I get the follow error.
Error in editDLfromGPath(gPath,specs,strict,grep,global,redraw):
'gPath' (geom_point.points) not found
Calls: grid.edit -> editDLfromGPath
Execution halted
Additionally a PDF is printed to my working directory called Rplots
. This plot is the default size and interestingly the points in the legend are thick but the points in the plot are not. It appears that the script fails at grid.edit()
but grid.draw()
succeeds.