Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 facet_wrap: only use x-axis labels existing in each group

I have the following dataset:

subj <- c(rep(11,3),rep(12,3),rep(14,3),rep(15,3),rep(17,3),rep(18,3),rep(20,3))
group <- c(rep("u",3),rep("t",6),rep("u",6),rep("t",6))
time <- rep(1:3,7)
mean <- c(0.7352941, 0.8059701, 0.8823529, 0.9264706, 0.9852941, 0.9558824, 0.7941176, 0.8676471, 0.7910448, 0.7058824, 0.8382353, 0.7941176, 0.9411765, 0.9558824, 0.9852941, 0.7647059, 0.8088235, 0.7968750, 0.8088235, 0.8500000, 0.8412698)
df <- data.frame(subj,group,time,mean)
df$subj <- as.factor(df$subj)
df$time <- as.factor(df$time)

And now I create a barplot with ggplot2:

library(ggplot2)
qplot(x=subj, y=mean*100, fill=time, data=df, geom="bar",stat="identity",position="dodge") +
   facet_wrap(~ group)

enter image description here

How do I make it so that the x-axis labels that are not present in each facet are not shown? How do I get equal distances between each subj (i.e. get rid of the bigger gaps)?

like image 444
absurd Avatar asked Jul 05 '15 06:07

absurd


People also ask

What is the difference between Facet_wrap and Facet_grid?

The facet_grid() function will produce a grid of plots for each combination of variables that you specify, even if some plots are empty. The facet_wrap() function will only produce plots for the combinations of variables that have values, which means it won't produce any empty plots.

What does Facet_wrap () help us do when added to a Ggplot?

facet_wrap() makes a long ribbon of panels (generated by any number of variables) and wraps it into 2d. This is useful if you have a single variable with many levels and want to arrange the plots in a more space efficient manner. You can control how the ribbon is wrapped into a grid with ncol , nrow , as.

How do I change X label in ggplot2?

To alter the labels on the axis, add the code +labs(y= "y axis name", x = "x axis name") to your line of basic ggplot code. Note: You can also use +labs(title = "Title") which is equivalent to ggtitle .

How do you remove facet labels?

To remove the label from facet plot, we need to use “strip. text. x” argument inside the theme() layer with argument 'element_blank()'.


1 Answers

You can use scale="free":

ggplot(df, aes(x=subj, y=mean*100, fill=time)) +
  geom_bar(stat="identity", position="dodge") +
  facet_wrap(~ group, scale="free") 

enter image description here

Another option with slightly different aesthetics using facet_grid. In contrast to the plots above, the panels aren't the same width here, but due to "space="free_x", the bars are the same widths.

ggplot(df, aes(x=subj, y=mean*100, fill=time)) +
  geom_bar(stat="identity", position="dodge") +
  facet_grid(~ group, scale="free", space="free_x")

enter image description here

like image 176
Jota Avatar answered Sep 21 '22 00:09

Jota