XM_Z
XM_Z

Reputation: 41

Add two more categories in ggplot2

I have a data set like this

df <- data.frame(ID=c("10","11","14","15","16","18","3","5","6","8","9","n"),
                 A=c("C","U","U","C","C","C","U","C","U","U","C","U"),
                 B=c("P","P","C","P","C","C","C","P","C","P","C","P"),
                 N=c(7,2,8,6,2,3,7,4,9,5,4,4))

ID is the identification number of each row. N is the value. A and B are two categories. I would like to create a bar plot or similar to compare N based on A and B category.

Here is my code:

ggplot(data=df,aes(x=ID,y=N,fill=A)) +
  geom_col(position="dodge")+
  facet_wrap(~B)

What I got is this: enter image description here

Here I hope I can put the same color together in each "C" and "P" category, and I would like to delete the empty columns from the graph, for example ID-10 in "C" cateogory.

I probably did not use the most appropriate way to make this figure, but this is what I can think of right now. If you have better ways to create the figure, could you help me please? Thank you!

Upvotes: 0

Views: 800

Answers (1)

aosmith
aosmith

Reputation: 36076

Using a "free" scale in facet_wrap() allows for different axis scales between panels. In this case you want to free the x axis so you can use scales = "free_x".

I interpreted the other part of your question to be about lumping the bars of specific colors together in each panel. This depends on what info you want to use to lump them. You could define the factor order, for example. Here, I create a new variable that pastes the "A" value before the "ID" value and uses that on the x axis so the "C" group is plotted before the "U" group. I call this new variable "combo".

This gets the A colors lumped together, but also changes the axis tick labels:

df$combo = with(df, paste(A, ID))

ggplot(data = df, aes(x = combo, y = N, fill = A)) +
    geom_col(position="dodge") +
    facet_wrap(~B, scales = "free_x")

Setting different axis labels when using free scales in facets is tricky, but can be done if you provide both the labels and breaks as shown in this SO answer.

Using that approach your code could be:

ggplot(data = df, aes(x = combo, y = N, fill = A)) +
    geom_col(position="dodge") +
    facet_wrap(~B, scales = "free_x") +
    scale_x_discrete(labels = df$ID, breaks = df$combo)

Created on 2021-06-24 by the reprex package (v2.0.0)

Upvotes: 1

Related Questions