Weird geom_path behavior

Viewed 133

I have noticed an odd behavior in geom_path() in ggplot2. I am not sure whether I am doing something wrong or whether it's a bug.

Here's my data set:

x <- abs(rnorm(10))
y <- abs(rnorm(10)/10)
categs <- c("a","b","c","d","e","f","g","h","i","j")

df <- data.frame(x,y,categs)

I make a plot with points and I join them using geom_path. Works well:

ggplot(df, aes(categs, x, group=1)) + geom_point() + geom_errorbar(aes(ymin=x-y, ymax=x+y)) + geom_path()

enter image description here

However, if I reorder my levels, for instance like this:

df$categs <- factor(df$categs, levels = c("f","i","c","g","e","a","d","h","b","j"))

enter image description here

then geom_plot still keeps the original order (although the order of the factor levels has been updated on the x axis).

Any guesses at what I am doing wrong? Thanks.

1 Answers

Order the df rows based on df$categs, geom_path goes row-by-row to plot:

ggplot(df[ order(df$categs), ], aes(categs, x, group=1)) + 
  geom_point() + 
  geom_errorbar(aes(ymin=x-y, ymax=x+y)) + 
  geom_path()

From ?geom_path manual:

geom_path() connects the observations in the order in which they appear in the data.

Related