Change the position of bars in ggplot2

Hello - My data looks like that:

library(ggplot2)
library(ggpattern)
set.seed(42)

f1 <- expand.grid(
  comp = LETTERS[1:3],
  exp = c("experiment 1", "experiment 2"),
  geneID = paste("Gene", 1:4)
)
f1$logfc <- rnorm(nrow(f1))
f1$SE <- runif(nrow(f1), min=0, max=1.5)

I want to generate a grouped bar plot to show the logfc value of each geneID for experiment 1 and experiment 2 (with and without pattern) for each comparison (colors). With this code bellow every thing is ok , however the logfc values for the geneID for each experiment is not glued side by side. What is the best way I can edit this code to have this. I just want for the values for experiment 1 ( without pattern) and experiment 2 (with pattern) should be side by side as shown here in this post. Here is my current code:

ggplot(f1, aes(x = geneID, y = logfc)) +
  geom_col_pattern(
    aes(pattern = exp,
        fill = interaction(exp, comp)), # <- make this an interaction
    colour = "black",
    pattern_fill = "black",
    pattern_angle = 45,
    pattern_density = 0.1,
    pattern_spacing = 0.01,
    position = position_dodge2(preserve = 'single'),
  ) +
  geom_errorbar(
    aes(
      ymin = logfc,
      ymax = logfc + sign(logfc) * SE,
      group = interaction(geneID, comp, exp)
    ),
    position = "dodge"
  ) +
  scale_pattern_manual(
    values = c("none", "stripe"),
    guide = guide_legend(override.aes = list(fill = "grey70")) # <- make lighter
  ) +
  scale_fill_manual(
    # Have 3 colours and repeat each twice
    values = rep(scales::hue_pal()(3), each = 2),
    # Extract the second name after the '.' from the `interaction()` call
    labels = function(x) {
      vapply(strsplit(x, "\\."), `[`, character(1), 2)
    },
    # Repeat the pattern over the guide
    guide = guide_legend(
      override.aes = list(pattern = rep(c("none", "stripe"), 3))
    )
  )

Thank you in advance!
Cheers

1 Like

Solved ! I have added aes(group=interaction(exp, comp) to the plot and its work

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.