Home > database >  Equally distributed bar chart in ggplot2
Equally distributed bar chart in ggplot2

Time:11-02

What I want to do

My dataset consists of several cases (id) with different outcomes (outcome) for a given number of repeated meaures (cycle). Each cycle should be counted as 1 (val) or be visualized of equal length. The plot I want to end up with is a stacked bar chart, where each cycle of each case has the same length. The sequence of cycles must be continous. The sequence of the outcomes is dependent on the according cycles.

My Problem

The sample code below produces a bar chart that sums up the cycles (although being a factor). However, using the val column instead of cycle messes with the sequence of the outcomes, which must not change.

# setup
library(ggplot2)
library(dplyr)    
set.seed(0)

# test data
data.frame(
  cycle=factor(rep(1:8,2),levels=1:8),
  val=1,
  id=factor(rep(1:2,each=8)),
  outcome=factor(paste("Outcome",sample(1:8,16,T)),levels=paste("Outcome",1:8))) %>%

  # plot
  ggplot(.,aes(id,cycle,fill=outcome)) 
  geom_bar(stat="identity",position=position_stack(reverse=T),width=0.99) 
  coord_flip()

My Question

Is it possible to make cycles count as 1 for each id, keeping the outcome sequence?

Thank you in advance!

The Plots

This is what I get when using the above code:

enter image description here

This is what I get, when using val instead of cycle:

enter image description here

The goal is to keep the outcome sequence, while counting each cycle as 1 or making them appear of the same length for each id.

CodePudding user response:

As far as I get it you could achieve your desired result using geom_tile:

library(ggplot2)

set.seed(0)

dat <- data.frame(
  cycle = factor(rep(1:8, 2), levels = 1:8),
  val = 1,
  id = factor(rep(1:2, each = 8)),
  outcome = factor(paste("Outcome", sample(1:8, 16, T)), levels = paste("Outcome", 1:8))
)

ggplot(dat, aes(cycle, id, fill = outcome))  
  geom_tile()

  • Related