Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Equally distributed bar chart in ggplot2

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading