【问题标题】:reorder ggplot2 axes on multiple levels在多个级别上重新排序 ggplot2 轴
【发布时间】:2018-09-15 07:06:23
【问题描述】:

我有一个数据框,melted_matrix:

 melted_matrix
          value  IndA  IndB            Culture Coverage Var1 Var2
1    0.00000000 1 1 Anatolia_Neolithic    9.431    1    1
2    0.02898616 2 1 Anatolia_Neolithic    6.948    2    1
3    0.02514688 3 1 Anatolia_Neolithic    9.765    3    1
4    0.07381144 4 1 Anatolia_Neolithic    1.213    4    1
5    0.17096256 5 1 Anatolia_Neolithic    0.231    5    1

我很高兴将其重新排序为一个级别(即分别用于 x 和 y 轴的 Var1 和 Var2:

hm.palette = colorRampPalette(rev(brewer.pal(11, 'Spectral')), space='Lab')
ggplot(melted_matrix, 
       aes(x = reorder(IndA, Var1), y = reorder(IndB, Var2), fill = value)) +  
  geom_tile() + 
  coord_equal() + 
  scale_fill_gradientn(colours = hm.palette(100))

我想按文化重新排序,然后按覆盖率。但是,如果我尝试添加更多级别:

ggplot(melted_matrix, 
       aes(x = reorder(IndA, Var1, Culture, Coverage), 
           y = reorder(IndB, Var2, Culture, Coverage), fill = value)) +  
  geom_tile() + 
  coord_equal() + 
  scale_fill_gradientn(colours = hm.palette(100))
Error in get(as.character(FUN), mode = "function", envir = envir) : 
  object 'FUN' of mode 'function' was not found

抛出一个错误。有没有办法在 ggplot 函数调用中添加更多级别,而不是搞乱数据框?

【问题讨论】:

  • 查看reorder() 的文档,我认为它只需要一个“排序”变量。因此,您将 Culture 传递给 FUN 参数,这会导致错误消息。一种可能的替代方法是首先根据所有变量对数据集进行排序,然后执行forcats::fct_inorder() 之类的操作来设置级别的顺序。
  • 这是一种可能的解决方案,因为就像@aosmith 所说,reorder() 只能采用一个辅助排序向量。 stackoverflow.com/questions/10758243/…

标签: r ggplot2


【解决方案1】:

我错过了什么吗?也许order() 而不是reorder? :

ggplot(melted_matrix, 
       aes(x = order(IndA, Var1, Culture, Coverage), 
           y = order(IndB, Var2, Culture, Coverage), fill = value)) +  
  geom_tile() + 
  coord_equal()

为了按照索引设置的正确顺序设置列 -

随便用

ggplot(melted_matrix, 
       aes(x = IndA[order(IndA, Var1, Culture, Coverage)], 
           y = IndB[order(IndB, Var2, Culture, Coverage)], fill = value)) +  
  geom_tile() + 
  coord_equal()

但这似乎有点简单,所以我觉得我可能不明白你想要什么:/

【讨论】:

    猜你喜欢
    • 2021-01-12
    • 2019-05-24
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    相关资源
    最近更新 更多