【问题标题】:geom_path grouped and path ordered by categorical factorgeom_path 分组和按分类因子排序的路径
【发布时间】:2021-11-18 06:15:19
【问题描述】:

我正在寻找一种解决方案,根据设置为因子的定义顺序对 geom_path 的路径进行排序。

我一直在使用前两个 PCA 维度。使用library("factoextra")library("FactoMineR") 我用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
)

数据按个体排列(以文本标签显示)。

使用geom_path 我想连接同一个人的点,按因子季节的路径排序,c(Autumn, Winter, Spring)。但是我很难做到这一点

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)
  )

设置为因子的排序似乎不会转化为 geom_path 路径的排序。

【问题讨论】:

  • 我相信geom_path使用的是出现的顺序而不是因子的顺序,所以你可能需要先添加一个排序步骤。

标签: r ggplot2 pca factominer


【解决方案1】:

这是一个较小的示例,比较原始版本和排序版本。 geom_path 是根据在数据中出现的顺序排序的,所以如果你希望它反映一个有序的因素,请先按那个排序。

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()

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

【讨论】:

  • 感谢 Jon,这个解决方案效果很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
  • 2014-07-24
  • 1970-01-01
  • 2018-01-06
  • 2019-04-13
  • 2021-04-25
相关资源
最近更新 更多