davide piu
davide piu

Reputation: 23

How can I do a function for plot both geom density and histogram?

I'm writing a function to plot both histogram and geom density plot :

attach(dati)


Graph_hist_dens <- function(X,Y,df) {
  ggplot(df,aes(x=X,..density..,fill=Y))+
  geom_histogram(binwidth = 1, color="black") +
  geom_density(alpha = 0.3,bw=4)+
  facet_grid(Y~.)
} 
Graph_hist_dens(TotOrd,AreaG,dati)

but when i run the function i get this error:

 Errore: At least one layer must contain all faceting variables:
* Plot is missing `Y`
* Layer 1 is missing `Y`
* Layer 2 is missing `Y

Upvotes: 0

Views: 75

Answers (1)

Marco Sandri
Marco Sandri

Reputation: 24262

Following the tutorial available at this link, two solutions can be developed.

library(ggplot2)
dati <- data.frame(TotOrd=rnorm(300), 
                   AreaG=rep(LETTERS[1:3],100))

Graph_hist_dens <- function(X, Y, df) {
  qX <- sym(X)
  qY <- sym(Y)
  ggplot(df,aes(x=!!qX, y=..density.., fill=!!qY))+
  geom_histogram(binwidth = 1, color="black") +
  geom_density(alpha = 0.3, bw=.4) +
  facet_wrap(vars(!!qY))
} 
Graph_hist_dens("TotOrd", "AreaG", dati)

Or

Graph_hist_dens <- function(X, Y, df) {
  eqX <- enquo(X)
  eqY <- enquo(Y)
  ggplot(df,aes(x=!!eqX, y=..density.., fill=!!eqY))+
  geom_histogram(binwidth = 1, color="black") +
  geom_density(alpha = 0.3, bw=.4) +
  facet_wrap(vars(!!eqY))
} 
Graph_hist_dens(TotOrd, AreaG, dati)

enter image description here

Upvotes: 1

Related Questions