passing parameters to ggplot
One solution would be to pass x and y as string names of columns in data frame DS.
f <- function(DS, x, y) {
ggplot(DS, aes_string(x = x, y = y)) + geom_point()
}
And then call the function as:
f(cars, "speed", "dist")
However, it seems that you don't want that? Can you provide an example why you would need different functionality? Is it because you don't want to have the arguments in the same data frame?
R - How to pass variables to ggplot
Using of aes_string
is deprecated, you can use sym
with !!
:
library(ggplot2)
library(rlang)
scatterWithRegLine = function(df, xColName, yColName, regMethod, showSe, showFullrange, size, yAxisLim) {
ggplot(df, aes(x = !!sym(xColName), y = !!sym(yColName))) +
geom_point() +
geom_smooth(method= regMethod, se=showSe, fullrange=showFullrange, size=size) + ylim(yAxisLim)
}
and then call it with
scatterWithRegLine(mtcars, "mpg", "wt", "loess", TRUE, FALSE, 1, c(0,5))
How to use a variable to specify column name in ggplot
Note: the solution in this answer is "soft-deprecated". See the answer below using .data[[
for the currently preferred method.
You can use aes_string
:
f <- function( column ) {
...
ggplot( rates.by.groups, aes_string(x="name", y="rate", colour= column,
group=column ) )
}
as long as you pass the column to the function as a string (f("majr")
rather than f(majr)
). Also note that we changed the other columns, "name"
and "rate"
, to be strings.
If for whatever reason you'd rather not use aes_string
, you could change it to (the somewhat more cumbersome):
ggplot( rates.by.groups, aes(x=name, y=rate, colour= get(column),
group=get(column) ) )
Passing an extra parameter to a custom geom in ggplot2
There is a relatively easy way, and that is to pass the extra parameter as argument to the panel drawing function. Here is a simple example that would work with your geom_simple_point()
:
GeomSimplePoint <- ggproto(
"GeomSimplePoint",
GeomPoint,
extra_params = c("na.rm", "showpoints"),
draw_panel = function(data, panel_params,
coord, na.rm = FALSE, showpoints = TRUE) {
if (showpoints) {
return(GeomPoint$draw_panel(data, panel_params, coord, na.rm = na.rm))
} else {
return(zeroGrob())
}
}
)
As an aside, if you want to replicate behaviour of an already existing geom, such as geom_point()
, it is easier to set your own ggproto object to inherit from that geom's ggproto object. That way, the default aes, required aes and other arguments that you specify in ggproto are automatically copied/inherited from that geom and you don't have to manually specify all of them.
R: How to pass parameters to ggplot geom_ within a function?
I like MSM's approach, but if you want to be able to add my_geom_y
to a ggplot you've already made, this is an alternative that might suit what you're after:
library(ggplot2)
x <- 1:100
my_geom_y <- function(yy, colour = "black"){
list(
geom_line(mapping = aes(y= yy),
col = colour),
data = data.frame(x, yy),
geom_point(mapping = aes(y = yy),
col = colour,
data = data.frame(x, yy))
)
}
ggplot(mapping = aes(x)) +
my_geom_y(x, "red") +
my_geom_y(dlnorm(x), "blue") +
my_geom_y((x^1.1), "black") +
my_geom_y(x/2, "yellow")
Passing extra parameters into the stat function
When you sepcify stat="summary"
, it still needs to know how to summarize your values. The default is to use the mean with standard errors. But you want medians with min and max values. You can write your own summary function
median_min_max <- function(x) {
data.frame(y=median(x), ymin=min(x), ymax=max(x))
}
And then pass that to your pointrange layer via the fun.data=
parameter.
ggplot(data = diamonds) +
geom_pointrange(
mapping = aes(x = cut, y = depth),
stat = "summary", fun.data = median_min_max
)
This will give you a plot that matches the one you created from your summarized data.
ggplot
does have a median_hilow
summary function but that uses the Hmisc::smedian.hilow
function which uses quantiles based on a confidence inteval rather than min/max values.
R- pass argument to ggplot in function
Based on the function arguments, it seems like convert
is flip
. Instead of using get
to modify the 'x' argument, we can do this with mutate
after converting the arguments to quosures
myfunction<- function(mydata, x, y, convert = FALSE){
x <- enquo(x)
y <- enquo(y)
xnew <- quo_name(x)
if (convert) {
mydata %>%
mutate(!! (xnew) := 1- !!(x)) %>%
ggplot(., aes_string(xnew, quo_name(y))) +
geom_line() +
xlab(paste0("1 - ", xnew))
} else {
ggplot(mydata, aes_string(xnew, quo_name(y))) +
geom_line()
}
}
myfunction(df1, x1, x2, convert = TRUE)
-output
myfunction(df1, x1, x2, convert = FALSE)
-output
data
df1 <- structure(list(x1 = c(0.1, 0.3, 0.4), x2 = c(0.2, 0.5, 0.6),
x3 = c(0.3, 0.7, 0.8), x4 = c(0.4, 0.9, 0.2)), .Names = c("x1",
"x2", "x3", "x4"), class = "data.frame", row.names = c(NA, -3L
))
Related Topics
Collapsing/Hiding Figures in R Markdown
Faster Way to Subset on Rows of a Data Frame in R
R Dplyr Filter Not Masking Base Filter
How to Self Join a Data.Table on a Condition
How to Expand an Ellipsis (...) Argument Without Evaluating It in R
Importing Only Every Nth Row from a .CSV File in R
How to Extract Substring Between Patterns "_" and "." in R
How to Pass Input Variable to SQL Statement in R Shiny
Apply T-Test on Many Columns in a Dataframe Split by Factor
Trying to Use Dplyr to Group_By and Apply Scale()
R Reshape a Vector into Multiple Columns
Using a Static (Prebuilt) PDF Vignette in R Package
What Does the Double Percentage Sign (%%) Mean
Merge Data Frames and Overwrite Values
Group by in R, Ddply with Weighted.Mean
How to Make PDF Download in Shiny App Response to User Inputs