temor
temor

Reputation: 1029

remove x axis labels for ggplot2?

giving the following data:

    data2 <- list(structure(list(super_group = c(1,1), Group.1 = structure(3:4, .Label = c("A","B", "C", "D", "E", "F"), class = "factor"), Pr1 = c(65, 75), Pr2 = c(54, 88), Prh = c(25, 5), SE = c(25, 75 )), row.names = c(NA, -2L), class = "data.frame"), NULL, structure(list(super_group = c(3,3), Group.1 = structure(3:4, .Label = c("A","B", "C", "D", "E", "F"), class = "factor"), Pr1 = c(81,4), Pr2 = c(66, 57),Prh = c(3,3), SE = c(8, 9)), row.names = c(NA,
-2L), class = "data.frame"))

to plot using ggplot2:

 data2 %>%
 bind_rows() %>%
 ggplot(., aes(x = Group.1, y = Pr1, fill = Group.1)) +
 geom_bar(stat = "identity") +
 facet_grid(. ~ super_group)

-you see C and D labels in the x axis which are not necessary. So I want to remove them and reduce the width of the bars. any ideas?

-can we move 1 and 3 from x axis top to x axis bottom?

Upvotes: 1

Views: 12388

Answers (1)

missuse
missuse

Reputation: 19756

We could use switch argument to facet_grid to change the position of facet labels.
Arguments axis.text.x and axis.ticks.x control the text and tick on the x axis. To remove them declare them as element_blank().

library(tidyverse)
data2 %>%
  bind_rows() %>%
  ggplot(., aes(x = Group.1, y = Pr1, fill = Group.1)) +
  geom_bar(stat = "identity") +
  facet_grid(. ~ super_group, switch = "x") +
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank()) -> p1

enter image description here

To change the proportions of the graph save it with different dimensions. Example:

ggsave("p1.pdf", plot = p1, device = "pdf", width = 3, height = 5)

Or if using knitr change the chunk options by defining:

fig.width=3, fig.height=5 for example:

```{r p1, fig.width=3, fig.height=5}  
data2 %>%
      bind_rows() %>%
      ggplot(., aes(x = Group.1, y = Pr1, fill = Group.1)) +
      geom_bar(stat = "identity") +
      facet_grid(. ~ super_group, switch = "x") +
      theme(axis.text.x = element_blank(),
            axis.ticks.x = element_blank())
``` 

and to change the width of the bars use argument width:

data2 %>%
  bind_rows() %>%
  ggplot(., aes(x = Group.1, y = Pr1, fill = Group.1)) +
  geom_bar(stat = "identity", width = 0.5) +
  facet_grid(. ~ super_group, switch = "x") +
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank())

enter image description here

another option (based on the comments it seems to me this is the desired one) is to change expand:

data2 %>%
  bind_rows() %>%
  ggplot(., aes(x = Group.1, y = Pr1, fill = Group.1)) +
  geom_bar(stat = "identity") +
  facet_grid(. ~ super_group, switch = "x") +
  scale_x_discrete(expand = c(1,1))+
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank())

enter image description here

Upvotes: 4

Related Questions