Making Plot Functions with Ggplot and Aes_String

Making plot functions with ggplot and aes_string

facet_wrap expects a formula as its first argument, so I'd just coerce it with as.formula, and feed in my sp as a string:

flowerPlotWrap <- function(dat, sl, sw, pl, sp){
ggplot(data=dat, aes_string(x=sl, y=sw, color=pl)) +
geom_point() +facet_wrap(as.formula(sp)) # note the as.formula
}
pl.flower3 <- flowerPlotWrap(iris, sl='Sepal.Length',
sw='Sepal.Width', pl='Petal.Length',
sp= '~Species')

Alternatively if my formula was always going to look like ~[columnname], I could just build that in to flowerPlotWrap and pass in the column name:

flowerPlotWrap <- function(dat, sl, sw, pl, sp){
ggplot(data=dat, aes_string(x=sl, y=sw, color=pl)) +
geom_point() +facet_wrap(as.formula(sprintf('~%s',sp)))
}
pl.flower3 <- flowerPlotWrap(iris, sl='Sepal.Length',
sw='Sepal.Width', pl='Petal.Length',
sp= 'Species')

(kudos to the reproducible example in your question! If everyone asked questions as well as that they'd get answers much quicker).

r - make plotting function with ggplot2, aes_string and reorder

With the latest version of ggplot, you should be use aes with !! and sym() to turn your strings into symbols.

myplot <- function(df, filtval, var1, var2) {
data <- df %>% filter(id == filtval)

ggplot(data) +
geom_point(
aes(
x = reorder(!!sym(var1), !!sym(var2)),
y = !!sym(var2))
)
}

How do I write a function for a plot in ggplot2 using correctly aes?

Use aes_string instead of aes. It should work. Worked for me :)

Note: Remove the quotes around your arguments in the function definition. Also your cor6 should be in quotes. See below

test <- function(explanatory,response)
{
plot<- ggplot(d, aes_string(x =explanatory, y=response)) +
geom_point()+
ggtitle("Correlation between Fertilizer and Yield") +
theme(plot.title = element_text(size = 10, face = "bold"))+
geom_smooth(method=lm, se=FALSE) +
annotate("text", x=800, y=20, size=5,label= "cor6")
plot
}

Does aes_string() change any default settings in R? A problem with R Shiny and ggplot input$ interaction

Your selection5 was an issue. The following code gives a reactive data frame.

  #example model
selection5 <- reactive({
# df <- iris[, c(input$xcol5, input$ycol5, 'Species')] ## this call does not work
df <- data.frame(x=iris[[input$xcol5]], y=iris[[input$ycol5]], Species=iris[, "Species"])
})

how to use aes_string for groups in ggplot2 inside a function when making boxplot

Aes_string evaluates the entire string, so if you do sprintf("factor(%s)",Variable1) you get the desired result. As a further remark: your function has a data-argument, but inside the plotting you use myData. I have also edited the x-lab and title, so that you can pass 'Variable3' and get proper labels.

With some example data:

set.seed(123)
dat <- data.frame(Variable2=rnorm(100),Variable1=c(0,1),Variable3=sample(0:1,100,T))

myfunction = function (data, Variable1) {
ggplot(data=data, aes_string(sprintf("factor(%s)",Variable1), "Variable2"))+
geom_boxplot(fill="grey", colour="black")+
labs(title = sprintf("%s and Variable2", Variable1)) +
labs (x = Variable1, y = "Variable2")
}

p1 <- myfunction(dat,"Variable1")
p2 <- myfunction(dat,"Variable3")

Sample Image

using function on colum name with aes_string in ggplot graph

There's probably a few ways of doing this. I'd extract elements from the dataframe by name and transform them before plotting.

for(label in c('bla','blub')) {

temp_var <- log2(df[[paste0('y.', label)]])

g <- ggplot(df, aes(x=x, y= temp_var)) + geom_point()
print(g)
}

How to make a ggplot2 plot inside of an R function using a column name (string) as input?

Maybe this can help but not tested in lack of data:

#Code
norm.plot <- function(col_name, bw) {
temp_df = pitchbook[!is.na(pitchbook[col_name]), c(col_name)]
ggplot(temp_df, aes_string(x=col_name)) +
geom_histogram(color="blue", fill="cyan", binwidth = bw)
}

Use variables supplied to aes_string() in other ggplot functions

You can extract the y variable from your data inside the expand_limits and scale that by 5%:

expand_limits(y = c(0, max(data[, var])*1.05))

Which makes:

fig_fun <- function(data, var){
ggplot(data, aes_string(x = "wt", y = var)) +
geom_line() +
geom_point() +
expand_limits(y = c(0,max(data[, var])*1.05))) # picking the var column here
}

You will need an additional + scale_y_continuous(expand = c(0, 0)) to absolutely limit to those numbers.

But as others suggested, if you use the default value for expand parameter of scale_y_continuous you'd get what you want.
So scale_y_continuous(expand = c(0, 0.1)) would give you 10% extra space from your y axis boundaries on either side. Docs are here.

The expand_limits method is still useful if you want some more custom solutions.

Create ggplot2 function and specify arguments as variables in data as per ggplot2 standard functionality

With the devel version of ggplot2, we can pass unquoted arguments, convert it to quosure (with enquo) and evaluate it (!!)

ggfun <- function(dat, x.var, y.var){
x.var <- enquo(x.var)
y.var <- enquo(y.var)
ggp <- ggplot(data = dat,
aes(x = !! x.var,
y = !! y.var)) +
geom_point()

return(ggp)
}

ggfun(dat = mtcars, x.var = drat, y.var = hp)

For quoted strings, convert it to symbol with sym (from rlang) and do the evaluation

ggfun <- function(dat, x.var, y.var){
x.var <- rlang::sym(x.var)
y.var <- rlang::sym(y.var)
ggp <- ggplot(data = dat,
aes(x = !! x.var,
y = !! y.var)) +
geom_point()

return(ggp)
}

ggfun(dat = mtcars, x.var = "drat", y.var = "hp")

Sample Image


If we want to pass either quoted or unquoted, the quosure is changed to character (quo_name), then to symbol (sym) and evaluate (!!)

ggfun <- function(dat, x.var, y.var){
x.var <- rlang::sym(quo_name(enquo(x.var)))
y.var <- rlang::sym(quo_name(enquo(y.var)))
ggp <- ggplot(data = dat,
aes(x = !! x.var,
y = !! y.var)) +
geom_point()

return(ggp)
}

p1 <- ggfun(dat = mtcars, x.var = drat, y.var = hp)
p2 <- ggfun(dat = mtcars, x.var = "drat", y.var = "hp")

all.equal(p1, p2)
#[1] TRUE


Related Topics



Leave a reply



Submit