Neal Fultz
Neal Fultz

Reputation: 9687

Order of x-axis with geom_segment

I am trying to make a plot where the x-axis is discrete but not sorted alphabetically.

I have a data.frame:

df <- data.frame(x1=factor(c('z1', 'z2', 'z1', 'z2'), levels=c('z3','z2', 'z1')),
                 x2=factor(c('z1', 'z1', 'z2', 'z3'), levels=c('z3','z2', 'z1')),
                 y1=c(1,2,3,4),
                 y2=c(5,6,7,8))

When I use geom_point, the x-axis is ordered correctly, by the levels of the factor:

ggplot(df) + aes(x=x1, y=y1) + geom_point(aes(x=x1, y=y1))

enter image description here

When I add a geom_segment, the ordering is reset to alphabetical.

ggplot(df) + aes(x=x1, y=y1)+  geom_point() + geom_segment(aes(xend=x2, yend=y2))

enter image description here

How can I force the x-axis to go z3, z2, z1 ?

Upvotes: 4

Views: 1430

Answers (1)

aosmith
aosmith

Reputation: 36076

This has to do with having different factor levels per x variable (some discussion here and here ).

You can use scale_x_discrete(limits = levels(df$x2) ) or scale_x_discrete(drop = FALSE) as a work-around.

ggplot(df) +  
    aes(x=x1, y=y1) +
    geom_point() + 
    geom_segment(aes(xend=x2, yend=y2)) +
    scale_x_discrete(drop = FALSE )

enter image description here

Upvotes: 2

Related Questions