zach
zach

Reputation: 30983

Minimize drawing size of ggplot plots by ignoring zero-length variables

I have a dataframe that I would like to plot in a similar way to one of the examples on the ggplot2 bar-plot page. The example is this one:

ggplot(diamonds, aes(cut, fill=cut)) + geom_bar() + facet_grid(. ~ clarity)

My question is that imagine in the diamonds dataset there were no Ideal cut VV21 clarity diamonds:

newdiamonds <- diamonds[diamonds$clarity != "VVS2" & diamonds$cut != 'Ideal', ]
ggplot(newdiamonds, aes(cut, fill=cut)) + geom_bar() + facet_grid(. ~ clarity)

If you draw this plot the "Ideal" position is still there even though there is no bar to be drawn. Is it possible to suppress drawing of this unused space? In this case it is not useful but in my case I have two columns of variables - 'data', and 'grouping'. I would like to facet across 'grouping' and display by 'data'. For groups of 'grouping' where a member of 'data' doesn't have a value, I don't want ggplot to draw it.


EDIT

Along the lines of the the two answers I am looking for a graph that would look like this:

ggplot(newdiamonds, aes(cut, fill=cut)) + geom_bar() + coord_flip() + facet_grid(clarity~.)

But where each group may have only one or more 'cut' attributes in it. enter image description here

Upvotes: 3

Views: 274

Answers (2)

jbaums
jbaums

Reputation: 27388

ggplot plots all levels of the factor, regardless of whether a level occurs in the dataset or not. After subsetting the dataset, you need to drop the unused factor level 'Ideal':

library(ggplot2)
newdiamonds <- diamonds[diamonds$clarity != "VVS2" & diamonds$cut != 'Ideal', ]
newdiamonds$cut <- newdiamonds$cut[, drop=TRUE]
ggplot(newdiamonds, aes(cut, fill=cut)) + geom_bar() + facet_grid(. ~ clarity) +
  opts(axis.text.x=theme_text(angle=90, hjust=1))

ggplot2 drop factor levels

Upvotes: 4

Justin
Justin

Reputation: 43245

Alternatively, you can add the argument scales='free' to your facet_grid call.

ggplot(newdiamonds, aes(cut, fill=cut)) + geom_bar() + facet_grid(. ~ clarity, scales='free')

But I would choose the other answer, he just wrote it faster!

Upvotes: 3

Related Questions