问题
to simplify my daily R interactions, I'd like to set up default colors for all my plots. For example, let's say I want to have all plots made with red lines (like in gnuplot...:-) )
So far, here is a snippet of my .Rprofile
setHook(packageEvent("grDevices", "onLoad"),
function(...)
grDevices::X11.options(width = 14, height = 8, type = "Xlib", xpos = 600, ypos = 30, canvas = "grey87"))
suppressPackageStartupMessages( require(Defaults) )
suppressPackageStartupMessages( require(utils) )
suppressPackageStartupMessages( require(graphics) )
setDefaults("plot.default",frame.plot=FALSE, type='l', col=2)
What I do here is the following:
when the grDevices
package is loaded (by loading the graphics
package), I call the X11.options
with my prefered parameters: a wider box, light gray background, xlib calls (because I'm doing distant calls, and cairo in my current environment is just too slow (another problem to solve))
Then I silently load 3 packages, Defaults
, utils
and graphics
. The second one is needed to avoid a find
function error message.
Finally, the magic function setDefaults
set-up 3 parameters to the scatter plot function plot.default
. The 3rd parameter col
is not a parameter of plot.default
but one from the par()
function.
But, doing a setDefaults
call with par
doesn't work either.
Any solution is welcome...
回答1:
You can use the "plot.new"
hook to set default par
values each time a new graphics frame is opened. (The hook's workings are documented in ?plot.new
and ?setHook
)
In your case, just add this line to your .Rprofile:
setHook("plot.new", function() par(col = "red"))
回答2:
The parameters such as color are set on a per device basis, so when you close one device and create a new one all the parameters are set back to their default values. To do this I would create your own device function that opens the device then sets the parameters, something like:
mydev.new <- function(...) {
dev.new(...)
par(col='red')
}
You could obviously replace dev.new
with x11
or something else, but this is probably the most portable. Now you can open a new device using mydev.new
and the default color will be set to red.
Further if you run the command
options(device=mydev.new)
Then when you don't have a graphics device open and you run a plotting command, your function will be the one run to open a new plotting device and so the default will be red in that case as well. You could expand the mydev.new
function (or whatever you want to call it) to set other options, take arguments, etc. for different cases you may want to work with.
来源:https://stackoverflow.com/questions/12625931/how-to-set-a-color-by-default-in-r-for-all-plot-default-plot-or-lines-calls