-1

I'm using fct_reorder() to order the levels of my factors in ggplot. That works fine for individual plots. But when I use plot_grid() from cowplot, there is some kind of problem. For contrast, to the left, I've used a plot that has fixed factor levels, not using fct_reorder.

enter image description here

Edited: Here is the actual code I'm using:

#make the base 
myplot <-filter(summary_by_intensity_reshaped, str_detect(feature, "binary"), Frequency == "2Hz") %>%
ggplot(., aes(fct_reorder(feature, mean),mean,fill=Intensity, ymax=mean+sem, ymin=mean-sem)) 

#add the layers
myplot  + geom_bar(stat="identity", position=position_dodge()) + 
  geom_errorbar(aes(width=0.2),position=position_dodge(0.9)) + 
  labs(x="Behavior",y="Percent of Trials (%)") +
  scale_x_discrete(breaks=c("binary_flutter", "binary_hold", "binary_lift", "binary_jump","binary_rear", "binary_lick", "binary_guard", "binary_vocalize"), labels=c("Flutter", "Holding", "Lifting", "Jumping", "Rearing", "Licking", "Guarding", "Vocalizing"))+
  facet_grid(~Frequency)+
  theme(axis.text.x=element_text(angle=-90))

And the output looks like this: enter image description here

The problem arises when I try to use 'myplot' in plot_grid(). That's when it renders oddly as in the example below.

Alex
  • 779
  • 2
  • 7
  • 20

1 Answers1

1

I suspect you're using fct_reorder() incorrectly. plot_grid() just takes whatever plot you make and puts it into a grid.

library(ggplot2)
library(cowplot)
library(forcats)

p1 <- ggplot(mpg, aes(class, displ, color = factor(cyl))) + geom_point()    
p2 <- ggplot(mpg, aes(fct_reorder(class, displ, mean), displ, color = factor(cyl))) + 
        geom_point()
plot_grid(p1, p2)

enter image description here

From your x axis title in the plot on the right, it looks to me like you forgot to provide fct_reorder() with the vector to which it should apply the function.

Claus Wilke
  • 16,992
  • 7
  • 53
  • 104
  • Hi. Thanks for responding. To clarify, in my example, 'mean' isn't the function mean. mean is actually the name of my factor in my data.frame. I calculate the means and put them into a column. The plot looks fine if i plot it individually. It's when I try to use plot_grid where it renders like that. – Alex Apr 22 '18 at 22:16
  • Well, in any case, you'll have to provide a complete, reproducible example for us to provide more useful feedback. – Claus Wilke Apr 23 '18 at 00:09
  • See this question and answers for guidance. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Claus Wilke Apr 23 '18 at 00:10