lll lll - 1 year ago 221
R Question

R: how to change the number of columns in each row in facet_grid

Through ggplot, I have a plot like the following using the code below. But I cannot see the x-axis at all if I plot like this. I am wondering if there is any way to get around with that such as changing the number of columns in each row. I have tried

command in
but it does not allow me to do that.

ggplot(derivative, aes(x = factor(move), fill = factor(move)), colour = black)+
scale_fill_discrete(name="Relative Market Move",
breaks=c("neg.big", "neg.small", "pos.big", "pos.small"),
labels=c("Big Negative", "Small Negative", "Big Positive", "Small Positive"))+
scale_x_discrete(labels=c("Large Negative", "Small Negative", "large Positive", "Small Positive"))+
labs( x = "") +ylab("Count")

cramped faceted plot

Answer Source

You might be better off with a stacked bar plot and with the bars for the "negatives" pointing downward. This will save space and make it easier to see trends. For example:


First create some fake data:

dat = data.frame(index=rep(c("S&P 500","Shanghai","Hang Seng"), each=7),
                 year=rep(paste0(rep(2009:2015,each=2),rep(c("Sp","Au"),7)), 3),
                 replicate(3, sample(50:100,14*3)))
dat$big.neg = 300 - rowSums(dat[,3:5])
names(dat)[3:5] = c("big.pos","small.pos","small.neg")

# Set year order
dat$year = factor(dat$year, levels=dat$year[1:14])

# Melt to long format
dat = melt(dat, id.var=c("year","index"))

Now for the plot:

ggplot() +
  geom_bar(data=dat[dat$variable %in% c("big.pos","small.pos"),], 
           aes(x=year, y=value, fill=rev(variable)), stat="identity") +
  geom_bar(data=dat[dat$variable %in% c("big.neg","small.neg"),], 
           aes(x=year, y=-value, fill=variable), stat="identity") +
  geom_hline(yintercept=0, colour="grey40") +
  facet_grid(index ~ .) +
                    values=c("red","blue","orange","green")) +
  scale_y_continuous(limits=c(-200,200), breaks=seq(-200,200,100), 
                     labels=c(200,100,0,100,200)) +
  guides(fill=guide_legend(reverse=TRUE)) +
  labs(fill="") + theme_bw() +
  theme(axis.text.x=element_text(angle=-90, vjust=0.5)) 

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download