Search code examples
rggplot2facet-grid

How to create different x-axis with keeping all values in each panel?


Let's say, I have data like following example,

dat1 <- data.frame(group = c("a", "a","a", "a", "a", "b", "b", "b","b","b","b","b","c","c","c"),
                   subgroup = c(paste0("R", rep(1:5)),paste0("R", rep(1:7)),paste0("R", rep(1:3))),
                   value = c(5,6,0,8,2,3,4,5,2,4,7,0,3,4,0),
                   pp = c("AT","BT","CT","AA","AT","TT","RT","CC","SE","DN","AA","MM","XT","QQ","HH"))

I want to add some cut off as

dat1 = dat1[dat1$value > 2, ]

My code is

library(ggplot2)
pl <- ggplot(dat1, aes(y = pp, x = subgroup)) + 
        geom_point(aes(size=value)) +  
        facet_grid(cols = vars(group), scales="free", space="free")+ 
        ylab("names") +xlab(" ")
pl 

enter image description here

I want to see all the columns of each panel. For example in the first panel, there should be five subgroups, I see only three columns in the figure, but I just want to see all five columns even if below of cut off or zero. The second panel has 7 scales. After cut off, there are 6 columns, but I want to see all 7 scales even if it has zero.

How can I modify my code or make as this kind of plot?


Solution

  • You need to subset without dropping a level.

    dat1 <- data.frame(group = c("a", "a","a", "a", "a", "b", "b", "b","b","b","b","b","c","c","c"),
                   subgroup = c(paste0("R", rep(1:5)),paste0("R", rep(1:7)),paste0("R", rep(1:3))),
                   value = c(5,6,0,8,2,3,4,5,2,4,7,0,3,4,0),
                   pp = c("AT","BT","CT","AA","AT","TT","RT","CC","SE","DN","AA","MM","XT","QQ","HH"))
    
    dat1[dat1$value <= 2, 3] <- NA
    
    pl <- ggplot(dat1, aes(y = pp, x = subgroup)) + 
     geom_point(aes(size=value)) +  
     facet_grid(~group, scales="free_x", space = "free")+ 
     ylab("names") +xlab(" ") +
     scale_size(range = c(3,8))