[R] ggplot2 and facet_wrap help

francesca casalino francy.casalino at gmail.com
Mon Feb 18 12:04:47 CET 2013


Dear R experts,

I am trying to arrange multiple plots, creating one graph for each
size1 factor variable in my data frame, and each plot has the median
price on the y-axis and the size2 on the x-axis grouped by clarity:

library(ggplot2)

df <- data.frame(price=matrix(sample(1:1000, 100, replace = TRUE), ncol = 1))

df$size1 = 1:nrow(df)
df$size1 = cut(df$size1, breaks=11)
df=df[sample(nrow(df)),]
df$size2 = 1:nrow(df)
df$size2 = cut(df$size2, breaks=11)
df=df[sample(nrow(df)),]
df$clarity = 1:nrow(df)
df$clarity = cut(df$clarity, breaks=6)


mydf = aggregate(df$price, by=list(df$size1, df$size2, df$clarity),median)

names(mydf)[1] = 'size1'
names(mydf)[2] = 'size2'
names(mydf)[3] = 'clarity'
names(mydf)[4] = 'median_price'

# So my data is already in a "long" format I think, but when I do this:

ggplot(data=mydf, aes(x=mydf$size2, y=mydf$median_price,
group=as.factor(mydf$clarity), colour=as.factor(mydf$clarity))) +
geom_line() + facet_wrap(~ factor(mydf$size1))


I get this error:
"Error in layout_base(data, vars, drop = drop) :
  At least one layer must contain all variables used for facetting"

Can you please help me understand what I am doing wrong?
-fra



More information about the R-help mailing list