Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GGPlot: Different chart types in facets?

Tags:

r

ggplot2

I'm trying to find a solution on how to stack 2 charts like facets. One chart shows the data counts, while the second shows the percentage.

This is the post that inspired me: Stacke different plots in a facet manner

Currently, I create two independent charts:

set.seed(1)
trial.id <- sample(1:6, 1000, replace = TRUE, c(".35", ".25", ".2", ".15", ".04",   ".01"))
surv <- sample(0:1, 1000, replace = TRUE)

trial.df <- data.frame(cbind(trial.id, surv))

# chart with counts information
windows(height = 800, width = 1500)
plotEX1 <- ggplot(trial.df, aes(x = as.factor(trial.id) , fill = as.factor(surv))) + 
        geom_bar(stat = "bin") +
        ggtitle("Surival by Trial\n") +
        labs(x = "\nTrial", y = "Patients (#)\n") +
        scale_fill_discrete(name = "Survival") 
plotEX1

# chart with % information
windows(height = 800, width = 1500)
plotEX2 <- ggplot(trial.df, aes(x = as.factor(trial.id) , fill = as.factor(surv))) + 
        geom_bar(stat = "bin", position = "fill") +
        ggtitle("Surival by Trial\n") +
        labs(x = "\nTrial", y = "Patients (%)\n") +
        scale_fill_discrete(name = "Survival") 
plotEX2

trial.id represents the number of trials run. surv represents the number of times a trial was successful.

plotEX1 show a count of how many trials were run, along with success rate. plotEX2 is the same thing, but displays as a percent.

The goal is to see these two charts together, so it's easy for the reader to see what the trial counts were along with the percentage of success.

I think what's throwing me off is trying to melt the data. I tried a couple things, but can't seem to get it to work. Any help pointing me in the right direction would be appreciated!

Thanks!

like image 588
AlexP Avatar asked May 10 '26 09:05

AlexP


1 Answers

Following our comments, I would probably do something like this:

new_dat <- melt(list(trial.df,trial.df),id.vars = 1:2)
new_dat$trial.id <- factor(new_dat$trial.id)
new_dat$surv <- factor(new_dat$surv)
ggplot() +
    facet_wrap(~L1,nrow = 2,scales = "free_y") + 
    geom_bar(data = subset(new_dat,L1 == 1),
             aes(x = trial.id , fill = surv),
             stat = "bin", 
             position = "fill") +
    geom_bar(data = subset(new_dat,L1 == 2),
             aes(x = trial.id , fill = surv),
             stat = "bin") +
    ggtitle("Surival by Trial\n") +
    labs(x = "\nTrial", y = "Patients (%)\n") +
    scale_fill_discrete(name = "Survival") 

enter image description here

(And ignore the warnings.)

like image 90
joran Avatar answered May 12 '26 02:05

joran