Reputation: 15
This is my first question on stackoverflow so please correct me if the question is unclear.
I would like to assign geom attributes for ggplot2 to a variable for reuse in multiple plots. For example, let's say I want to assign the attributes of size and shape to a variable to resuse in plotting data other than mtcars.
This code works, but if I have a lot of plots I don't want to keep re-entering the size and shape attributes.
ggplot(mtcars) +
geom_point(aes(x = wt,
y = mpg),
size = 5,
shape = 21
)
How should I assign a variable (eg size.shape) these attributes so that I can use it in the below code to produce the same plot?
ggplot(mtcars) +
geom_point(aes(x = wt,
y = mpg),
size.shape
)
Upvotes: 1
Views: 908
Reputation: 15937
If you always want to use the same values for size
and shape
(or other aesthetics), you could use update_geom_defaults()
to set the default values to other values:
update_geom_defaults("point", list(size = 5, shape = 21))
These will then be used whenever you do not specifically give values for the aesthetics.
The plot you create with the usual default settings looks as follows:
ggplot(mtcars) + geom_point(aes(x = wt, y = mpg))
But when you reset the defaults for size
and shape
, it looks differently:
update_geom_defaults("point", list(size = 5, shape = 21))
ggplot(mtcars) + geom_point(aes(x = wt, y = mpg))
As you can see, the actual plot is done with the same code as before, but the result is different because you changed the default values for size
and shape
. Of course, you can still produce plots with any value for these aesthetics, by simply providing values in geom_point()
:
ggplot(mtcars) + geom_point(aes(x = wt, y = mpg), size = 2, shape = 2)
Note that the defaults are given by geom
, which means that only geom_point()
is affected.
This solution is convenient, if there is only one set of values for size
and shape
that you want to use. If you have several sets of values that you want to be able to pick from when creating a plot, then you might be better off with something along the lines of the comment by lukeA.
Upvotes: 1