Search code examples
dataframeplottraminer

TramineR legend position and axis


I'm working with TraMineR and I don't know how to arrange my plot. So basically what i would like to have the legend under the plot and to remove the space between the x and y axis. Any help is welcomed.

The plot:

enter image description here

Sample code:

seqdplot(Activities.seq, with.legend=FALSE)

legend("bottom", legend=attr(Activities.seq, "labels"), 
       fill=attr(Activities.seq, "cpal"), 
       inset=-.1, bty="o", xpd=NA, cex=.75,ncol=3)

Solution

  • The family of seqplot functions offers a series of arguments to control the legend as well as the axes. Look at the help page of seqplot (and of plot.stslist.statd for specific seqdplot parameters).

    For instance, you can suppress the x-axis with axes=FALSE, and the y-axis with yaxis=FALSE.

    To print the legend you can let seqdplot display it automatically using the default with.legend=TRUE option and control it with for examples cex.legend for the font size, ltext for the text. You can also use the ncol argument to set the number of columns in the legend.

    The seqplot functions use by default layout to organize the graphic area between the plots and the legend. If you need more fine tuning (e.g. to change the default par(mar=c(5.1,4.1,4.1,2.1)) margins around the plot and the legend), you should create separately the plot(s) and the legend and then organize them yourself using e.g. layout or par(mfrow=...). In that case, the separate graphics should be created by setting with.legend=FALSE, which prevents the display of the legend and disables the automatic use of layout.

    The color legend is easiest obtained with seqlegend.

    I illustrate with the mvad data that ships with TraMineR. First the default plot with the legend. Note the use of border=NA to suppress the too many vertical black lines.

    library(TraMineR)
    data(mvad)
    mvad.scode <- c("EM", "FE", "HE", "JL", "SC", "TR")
    mvad.seq <- seqdef(mvad, 17:86, 
                       states = mvad.scode,
                       xtstep = 6)
    
    # Default plot with the legend, 
    seqdplot(mvad.seq, border=NA)
    

    enter image description here

    Now, we suppress the x and y axes and modify the display of the legend

    seqdplot(mvad.seq, border=NA,
             axes=FALSE, yaxis=FALSE, ylab="",
             cex.legend=1.3, ncol=6, legend.prop=.11)
    

    enter image description here

    Here is how you can control the space between the plot and the x and y axes

    seqdplot(mvad.seq, border=NA, yaxis=FALSE, xaxis=FALSE, with.legend=FALSE)
    axis(2, line=-1)
    axis(1, line=0)
    

    Creating the legend separately and reducing the left, top, and right margins around the legend

    op <- par(mar=c(5.1,0.1,0.1,0.1))
    seqlegend(mvad.seq, ncol=2, cex=2)
    par(op)
    

    enter image description here