I would like to be able to merge 3 graphs to obtain a single graph. I used geom_bar()
from ggplot2
to create the 3 graphs. However, the position = "dodge"
function does not allow me to individualize them at each time of X (X1, X2, X3 ...).
The patchwork package
can't help me because it's not about combining graphs on a single figure but merging them. Merge only works for merging data frames.
Attached data :
id = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3),
reponse = c("12_vsys", "13_vsys", "14_vsys", "15_vsys", "16_vsys", "17_vsys", "18_vsys", "19_vsys", "20_vsys", "21_vsys", "22_vsys", "23_vsys", "24_vsys", "24_vsys", "12_vsys", "13_vsys", "14_vsys", "15_vsys", "16_vsys", "17_vsys", "18_vsys"),
inf_palu2 = c("0", NA, NA, NA, NA, NA, "0", NA, NA, NA, NA, NA, "0", NA, "0", NA, NA, NA, NA, NA, "2"),
inf_sympto2 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "1")),
d2 <- data.frame(id, reponse, inf_palu2, inf_sympto2)
Attached code graph :
library(ggplot2)
ggplot() +
geom_bar(d2, mapping = aes(x = reponse), position = "dodge", color = "blue") +
geom_bar(d2,mapping = aes(x = reponse, fill = inf_palu2),position = "dodge", color = "red") +
geom_bar(d2,mapping = aes(x = reponse, fill = inf_sympto2),position = "dodge", color = "yellow")
To do this, you need all of your columns of interest pivoted into a single column. It is not entirely clear what your desired outcome is. For instance, in the absence of a y aesthetic, ggplot2
defaults to counts. Given the presence of NAs in your data, this does not really makes sense. Comment below to clarify what you are trying to achieve, and I'll update the answer if necessary. Either way, here is a workflow to get you started:
library(dplyr)
library(tidyr)
library(ggplot2)
# Your data
id = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3)
reponse = c("12_vsys", "13_vsys", "14_vsys", "15_vsys", "16_vsys", "17_vsys", "18_vsys", "19_vsys", "20_vsys", "21_vsys", "22_vsys", "23_vsys", "24_vsys", "24_vsys", "12_vsys", "13_vsys", "14_vsys", "15_vsys", "16_vsys", "17_vsys", "18_vsys")
inf_palu2 = c("0", NA, NA, NA, NA, NA, "0", NA, NA, NA, NA, NA, "0", NA, "0", NA, NA, NA, NA, NA, "2")
inf_sympto2 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "1")
d2 <- data.frame(id, reponse, inf_palu2, inf_sympto2)
# Pivot d2 columns to long format
df <- d2 |>
pivot_longer(-c(id, reponse))
# Plot
ggplot() +
geom_bar(data = df, aes(x = reponse, fill = name),
colour = "#006ddb",
position = "dodge") +
scale_fill_manual(values = c("#DF536B", "#F0E442")) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5))