Search code examples
rplotaxisaxis-labels

R base graphics: customizing axis labels in grouped data


df <- data.frame(g1=c('A', 'A', 'B', 'B'),
                 g2=c('a', 'b', 'a', 'b'),
                 v1=1:4,
                 v2=4:1)

I am trying to make something like this where the two "group" variables g1 and g2 is labelled in the customized way indicated below - notice the small space between the two groups. I realize that if the x-axis goes from 0 to 10 then we have a, b, a, and b at 2, 4, 7 and 9 (more or less) and A and B at 3 and 8. But how can this be specified - in a call to axis() or text() ? I would like to do this in base R. schematic plot


Solution

  • One way would be

    df <- data.frame(g1=c('A', 'A', 'B', 'B'),
                     g2=c('a', 'b', 'a', 'b'),
                     v1=1:4,
                     v2=4:1)
    plot(df$v1, df$v1, xaxt = 'n', pch = 15)
    points(df$v2, df$v1, pch = 13)
    axis(1, at = df$v1, labels = df$g2)
    axis(1, at = c(1.5, 3.5), labels = unique(df$g1), line = 1, tick = F)
    

    enter image description here