Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add second y axis to seqfplot with sequence frequency?

Tags:

plot

r

traminer

I'm working with TraMineR to do a sequence analysis of educational data. I can get R to produce a plot of the 10 most frequent sequences in the data using code similar to the following:

library(TraMineR)

##Loading the data
data(actcal)

##Creating the labels and defining the sequence object
actcal.lab <- c("> 37 hours", "19-36 hours", "1-18 hours", "no work")
actcal.seq <- seqdef(actcal, 13:24, labels=actcal.lab)

## 10 most frequent sequences in the data
actcal.freq <- seqtab(actcal.seq)
actcal.freq

## Plotting the object
seqfplot(actcal.seq, pbarw=FALSE, yaxis="pct", tlim=10:1, cex.legend=.75, withlegend="right")

However, I'd also like to have the frequencies of each sequence (which are in the object actcal.freq) along the right side of the plot. For example, the first sequence in the plot created by the code above represents 37.9% of the data (as the plot currently shows). Per the seqtab, this is 757 subjects. I'd like the number 757 to appear on the right y-axis (and so on for the other sequences).

Is this possible? I've played around with axis(side=4, ...) but never been able to get it to reproduce the spacing of the left y-axis.

like image 761
Andrew Wallace Avatar asked Dec 04 '25 14:12

Andrew Wallace


1 Answers

OK. This is a bit of a mess, but the function resets the par setting if you include a legend by default, so you need to turn that off. Then you can set the axis a bit more easily, and then we can go back for the legend. This should work with your test data above.

#add padding to the right for axis and legend
par("mar"=c(5,4,4,8)+.1)

#plot w/o axis
seqfplot(actcal.seq, pbarw=FALSE, yaxis="pct", tlim=10:1, withlegend=F)

#plot right axis with freqs
axis(4, at = seq(.7, by=1.2, length.out=length(attr(actcal.freq,"freq")$Freq)), 
    labels = rev(attr(actcal.freq,"freq")$Freq), 
    mgp = c(1.5, 0.5, 0), las = 1, tick = FALSE)

#now put the legend on        
legend("right", legend=attr(actcal.seq, "labels"), 
    fill=attr(actcal.seq, "cpal"), 
    inset=-.3, bty="o", xpd=NA, cex=.75)

You may need to play a bit with the margins and especially the inset= parameter of the legend to get it placed correctly. I hope your real data isn't too much different than this because you really have to dig though the function to see how it does the formatting to get things to match up.

TraMineR plot with right y-axis

like image 61
MrFlick Avatar answered Dec 07 '25 02:12

MrFlick