Grouped reversed bar plot in ggplot2

Viewed 35

I would like to recreate this plot:

example_1.png

My data looks like this:

leafnumber <- c(6,7,8,9,6,7,8,9)
PU <- c(30,15,7,0,10,36,7,9)
weeknumber <- c(8,8,8,8,9,9,9,9)

df <- data.frame(leafnumber, PU, weeknumber)

So I want leafnumber to end up on the Y-axis and PU on the X-axis. And weeknumber can be used to show distribution over time.

Here is my first attempt:

ggplot(df,aes(leafnumber, PU)) +
  geom_bar(stat = "identity") +
  coord_flip()

I am not sure how to get from a bar plot to a 'grouped' barplot, like the one in the image.

The goal is to have this distribution for each weeknumber on the X-axis so I can see the distribution change within time.

What I do not mean is this:

ggplot(df,aes(leafnumber, PU, fill=weeknumber)) +
  geom_bar(stat = "identity") +
  coord_flip()

Any suggestions/solutions for this problem would be appreciated.

1 Answers

If your actual dataset has a large number of observations for each leaf / PU, you can use the ggridges package to get a similar plot, e.g.

library(tidyverse)
library(ggridges)

# Make 'larger' fake data
leafnumber <- c(runif(1, 6, n = 100),
                runif(3, 9, n = 100),
                runif(5, 12, n = 100),
                runif(10, 15, n = 100),
                runif(15, 18, n = 100))

PU <- factor(c(rep("1", 100), rep("2", 100),
        rep("3", 100), rep("4", 100), rep("5", 100)),
        levels = c("1", "2", "3", "4", "5"))

weeknumber <- c(8,8,8,8,8,9,9,9,9,9)

df <- data.frame(leafnumber, PU, weeknumber)

# Plot the data
ggplot(df, aes(x = leafnumber, y = PU, height = stat(density))) + 
  geom_density_ridges(stat = "binline", bins = 40,
                      scale = 0.95, draw_baseline = FALSE) +
  coord_flip()

example_1.png

Related