Liquidity
Liquidity

Reputation: 625

ggplot: stacking graphs with x-axis labels only on bottom graph

I have a dataframe like this:

ID <- c("A1", "A2", "A3", "A4", "A5", "A6")
group <- c("Cats", "Cats", "Cats", "Dogs", "Dogs", "Dogs")
value <- c(5, 10, 20, 5, 15, 30)

data <- data.frame(ID, group, value)

When I graph it using this code

ggplot(data, aes(group, value, color=group)) + geom_jitter(show.legend = FALSE) + labs(x = " ") +
  theme_bw(base_size=20) + theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1)) 

I get this result

enter image description here

I have a couple dataframes that I want to graph together, but when I use grid.arrange I get a result that has the x-axis labeled on both graphs:

enter image description here

Since the x-axis is the same, my desired output has the x-axis labeled only on the bottom graph, like this:

enter image description here

Is this possible in ggplot?

Upvotes: 0

Views: 549

Answers (1)

bjorn2bewild
bjorn2bewild

Reputation: 1019

Perhaps you could bind the data frames together and then use facet_grid

ID <- c("A1", "A2", "A3", "A4", "A5", "A6")
group <- c("Cats", "Cats", "Cats", "Dogs", "Dogs", "Dogs")
value <- c(5, 10, 20, 5, 15, 30)
value2 <- c(8, 13, 23, 8, 18, 50)

data <- data.frame(ID, group, value, whichdf = "1")
data2 <-data.frame(ID, group, value = value2, whichdf = "2") 

df <- rbind(data,data2)

ggplot()

ggplot(df, aes(group, value, color=group)) + 
  facet_grid(vars(whichdf)) +
  geom_jitter(show.legend = FALSE) + 
  labs(x = " ") +
  theme_bw(base_size=20) + 
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))

Which yields

enter image description here

If the y-axis values vary greatly, you can specify scales = "free" within facet_grid for each plot to have their own y-axis scale.

Upvotes: 1

Related Questions