Andrew Redd
Andrew Redd

Reputation: 4692

Change stack order of True and False in R/ggplot2

When plotting logical values with qplot in ggplot2 the False counts are always on the bottom, but more often than not I want True on the bottom so that it is easier to read. Here is an example

y<-as.logical(rbinom(100,1,0.7))
x<-factor(rep(letters[1:2], each=50))
qplot(x,fill=y, geom='bar')

How can I get the counts for TRUE on the bottom of the stack?

Upvotes: 6

Views: 1614

Answers (1)

Matt Parker
Matt Parker

Reputation: 27359

If you're comfortable converting to a factor, you could do this:

yf <- factor(y, levels = c("TRUE", "FALSE"))
qplot(x, fill = yf, geom = 'bar')

I'd just be sure to keep your original logical vector and only use the factor for plotting. Hard to know what effects using the factor in lieu of the logical could have downstream.

Upvotes: 5

Related Questions