2016-03-11 3 views
2

У меня возникают проблемы с использованием grid.edit() от Rscript. Я использую grid.edit() для увеличения толщины полых точек в легенде и диаграмме. Я взял это с этой должности (Change thickness of a marker in ggplot2). Просто выглядит лучше ИМО. Я знаю, что из исходных файлов и Rscripts вы можете получить ggplot объектов для построения с использованием print(p), но мне нужно использовать grid.edit(), поэтому я не уверен, как это исправить. Ниже приведен рабочий пример.Проблемы с использованием grid.edit() в Rscript

Мой 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() преуспевает.

+0

Я построил Rscript данным периодического процесса и производить набор графиков. Я хочу распространять это на других людей в моем офисе, которые не знают R. Любой, у кого есть подключение к сетевому диску, может запускать скрипт с их локального компьютера, и скрипт будет обрабатывать файлы в каталоге пакетного файла. Могу ли я использовать Rterm и создать Rprofile, который управлял командами напрямую или использовал 'source()' в начале сеанса R, чтобы получить тот же результат или будет использовать 'source()' для запуска в те же проблемы? – CCurtis

+1

Попробуйте это: добавьте 'grid.force()' непосредственно перед 'grid.edit (....' line. 'Grid.force()' делает grob видимыми для функций редактирования сетки. Без 'grid.force() ', функции редактирования видят только один grob. –

+0

Он избавился от ошибки, но результат в том же. Не похоже, что grid.edit выполняет свою работу. Спасибо, полезно знать. Думаю, я мог бы попытаться создать shiny app – CCurtis

ответ

2

Необходимо, чтобы график, чтобы функции редактирования сетки могли видеть все грызуны. Я увеличил размер точки и множитель ширины линии, так что очевидно, что редактирование вступило в силу.

library(ggplot2) 
library(grid) 
library(gtable) 

p <- ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(shape = factor(cyl)), size = 5) + scale_shape(solid = FALSE) 
lwd = 3 # 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.ls() 
grid.ls(grid.force()) # Note the difference here 

grid.force() 
grid.edit("geom_point.points", grep = TRUE, gp = gpar(lwd = lwd)) 


# Or to edit the grob (rather than edit on screen) 
g = editGrob(grid.force(g), "geom_point.points", grep = TRUE, gp = gpar(lwd = lwd)) 
grid.newpage() 
grid.draw(g) 

# To give it a print method 
print.ggplotgrob <- function(x) { 
    grid.newpage() 
    grid.draw(x) 
} 
class(g) = c("ggplotgrob", class(g)) 

g 

enter image description here

Мои sessionInfo()

R version 3.2.3 (2015-12-10) 
Platform: x86_64-w64-mingw32/x64 (64-bit) 
Running under: Windows 7 x64 (build 7601) Service Pack 1 

locale: 
[1] LC_COLLATE=English_Australia.1252 LC_CTYPE=English_Australia.1252 
[3] LC_MONETARY=English_Australia.1252 LC_NUMERIC=C      
[5] LC_TIME=English_Australia.1252  

attached base packages: 
[1] grid  stats  graphics grDevices utils  datasets methods 
[8] base  

other attached packages: 
[1] Cairo_1.5-9 gtable_0.2.0 ggplot2_2.1.0 

loaded via a namespace (and not attached): 
[1] labeling_0.3  colorspace_1.2-6 scales_0.4.0  plyr_1.8.3  
[5] tools_3.2.3  Rcpp_0.12.3  digest_0.6.9  munsell_0.4.3 
+0

Пригвожденный! Угадайте, я сдался досрочно. Прекрасно работает. применил это к моим фактическим диаграммам, обеспечивающим, что метод печати не работал, и необходимо было использовать «grid.newpage» и «grid.draw», но здесь не было никаких жалоб. Очень рад, что это работает. Большое спасибо. – CCurtis

+0

делать с версией ggplot2. Метод печати не будет работать со старыми версиями. –

+1

Ya его было несколько месяцев с тех пор, как я обновил. Думаю, придется сделать обновление. – CCurtis

Смежные вопросы