In R - How do you make transition charts with the Gmisc package?

762 Views Asked by At

I've been trying to make a graph that looks like this (but nicer)

Rudimentary Flow Chart

based on what I found in this discussion using the transitionPlot() function from the Gmiscpackage.

However, I can't get my transition_matrix right and I also can't seem to plot the different state classes in separate third column.

My data is based on the symptomatic improvement of patients following surgery. The numbers in the boxes are the number of patients in each "state" pre vs. post surgery. Please note the (LVAD) is not a necessity.

The data for this plot is this called df and is as follows

dput(df)
structure(list(StudyID = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 
7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L), .Label = c("P1", "P2", "P3", 
"P4", "P5", "P6", "P7"), class = "factor"), MeasureTime = structure(c(2L, 
2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Postoperative", 
"Preoperative"), class = "factor"), NYHA = c(3L, 3L, 3L, 3L, 
3L, 2L, 3L, 1L, 3L, 1L, 3L, 3L, 1L, 1L)), .Names = c("StudyID", 
"MeasureTime", "NYHA"), row.names = c(NA, -14L), class = "data.frame")

I've made a plot in ggplot2 that looked like this

ggplot2 image

but my supervisor didn't like it, because I had to jitterthe lines so that they didn't overlap and so one could see what was happening with each patient and thus the points/lines aren't exactly lined up with the y-axis.

So I was wondering if anyone had an idea, how I'd be able to do this using the Gmisc package making what seems to me to be a transitionPlot.

Your help and time is much appreciated.

Thanks.

1

There are 1 best solutions below

2
MrFlick On BEST ANSWER

Using your sample df data, here are some pretty low-level plotting function that can re-create your sample image. It should be straigtforward to customize however you like

First, make sure pre comes before post

df$MeasureTime<-factor(df$MeasureTime, levels=c("Preoperative","Postoperative"))

then define some plot helper functions

textrect<-function(x,y,text,width=.2) {
    rect(x-width, y-width, x+width, y+width)
    text(x,y,text)
}
connect<-function(x1,y1,x2,y2, width=.2) {
    segments(x1+width,y1,x2-width,y2)   
}

now draw the plot

plot.new()
par(mar=c(0,0,0,0))
plot.window(c(0,4), c(0,4))

with(unique(reshape(df, idvar="StudyID", timevar="MeasureTime", v.names="NYHA", direction="wide")[,-1]), 
    connect(2,NYHA.Preoperative,3,NYHA.Postoperative)
)
with(as.data.frame(with(df, table(NYHA, MeasureTime))), 
    textrect(as.numeric(MeasureTime)+1,as.numeric(as.character(NYHA)), Freq)
)

text(1, 1:3, c("I","II","III"))
text(1:3, 3.75, c("NYHA","Pre-Op","Post-Op"))
text(3.75, 2, "(LVAD)")

which results in

enter image description here