1

I have tried to make barplots in ggplot2 in a loop, each loop with this code

up <- data.frame(X = c("A", "B", "C"),
                 Y = sample(1:3))


down <- data.frame(X = c("F", "G", "H", "I"),
                   Y = sample(1:4))
up$type <- "up"
down$type <- "down"
gos <- rbind(down,up)

gos$X <- factor(gos$X, levels=gos$X)

# Diverging Barcharts
g <- ggplot(gos, aes(x=X, y=Y , label=Y)) + 
  geom_bar(stat='identity', aes(fill=type), width=.5,position="dodge") +
  scale_fill_manual(name="Expression", 
                    labels = c("Down regulated", "Up regulated"), 
                    values = c("down"="#00ba38", "up"="#f8766d")) + 
  labs(title= "Biological process") + 
  coord_flip()
g

Because of the number of observers changes in the loop, I don't have a fixed number of bar per barplot. For example, in this case, I got 3 bars in the up category, 4 bars in the down category.

However, for better visual, I want to make the structure of the plot fixed, and the empty observer will be left empty in the barplot. For example: I want all of them has this structure, 5 bars in each category, the empty bar will still be kept (without anydata) enter image description here

How can I do this using ggplot2 in R? Thank you very much

Thanh Nguyen
  • 902
  • 2
  • 12
  • 31
  • Try using facets: `facet_wrap(~ Term)` – pogibas May 26 '19 at 15:53
  • 1
    Could you make your problem reproducible by sharing a sample of your data so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung May 26 '19 at 15:56
  • Yes, I have provided the example data – Thanh Nguyen May 26 '19 at 17:14
  • 1
    @ThanhNguyen: That's not helpful. Please do read the links I posted – Tung May 27 '19 at 01:11
  • @Tung: hi, I have revamped the question according to the link. I'm not so good at coding by R, so sorry – Thanh Nguyen May 27 '19 at 02:29
  • Will these help? https://www.aj2duncan.com/blog/missing-data-ggplot2-barplots/ – Tung May 27 '19 at 03:33
  • https://stackoverflow.com/questions/45633109/how-do-i-keep-a-constant-width-bar-chart-in-rs-ggplot2-when-there-are-redundant – Tung May 27 '19 at 03:33
  • Yes, I have checked out that answer. However, in my data, I don't have any values if my list is shorter than a destined length (including the label name), so when I used `gos$X <- factor(gos$X, levels=gos$X)` , the factor is said to be duplicated and cannot be processed. – Thanh Nguyen May 27 '19 at 03:37

0 Answers0