Skip to content

ggplot2 and facet_wrap help

3 messages · Ista Zahn, francesca casalino

#
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
#
Hi,

You are making it more complicated than it needs to be. You already
provided the data.frame in the ggplot call, so you don't need to
specify it in the aes calls. The various factor() and as.factor()
calls are also unnecessary. So stripping away this extra stuff your
plot looks like

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

which does give the desired display.

Best,
Ista

On Mon, Feb 18, 2013 at 6:04 AM, francesca casalino
<francy.casalino at gmail.com> wrote:
#
Dear Ista,

Thank you! It works perfectly!
-fra

2013/2/18 Ista Zahn <istazahn at gmail.com>: