1

I am looking for a solution to order the pathway of geom_path based on a defined order set to a factor.

I have been working with the fist two PCA dimensions. Using library("factoextra") and library("FactoMineR") I generate my figure with fviz_pca_ind().

raa_male <- fviz_pca_ind(
  pca.data,
  fill.ind = male_raa.df$Season,
  pointsize = male_raa.df$BRI,
  pointshape = 21,
  repel = TRUE
)

The data is arranged in to individuals (shown by text labels).

enter image description here

Using geom_path I want to connect points of the same individual, by order the path way the factor season, c(Autumn, Winter, Spring). However I am having difficulty doing this

male_raa.df$Season <- factor(male_raa.df$Season, levels = c("Autumn", "Winter", "Spring"))

raa_male +
  geom_path(
    arrow = arrow(angle = 15, ends = "last", type = "closed"),
    alpha = 0.2,
    aes(group = male_raa.df$TagID)
  )

enter image description here

The ordering set to factor does not appear translating to ordering of the geom_path pathway.

utubun
  • 4,400
  • 1
  • 14
  • 17
bennh
  • 11
  • 2
  • 1
    I believe `geom_path` uses the order of appearance rather than order of the factor, so you may need to add a sorting step first. – Jon Spring Nov 18 '21 at 06:32

1 Answers1

1

Here's a smaller example, compare the original and sorted version. geom_path is ordered based on the order of appearance in the data, so if you want it to reflect an ordered factor, sort by that first.

df1 <- data.frame(x = 1:3,
                  y = c(1,2,1),
                  season = LETTERS[1:3])
df1$season = factor(df1$season, levels = c("B","C","A"))

library(ggplot2); library(dplyr)
ggplot(df1, aes(x,y, label = season)) +
    geom_path(arrow = arrow(angle = 15, ends = "last", type = "closed")) +
    geom_label()

enter image description here

ggplot(df1 %>% arrange(season), aes(x,y, label = season)) +
    geom_path(arrow = arrow(angle = 15, ends = "last", type = "closed"),) +
    geom_label()

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53