0

I have a data frame, 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

I am happy reordering it by a single level (i.e. Var1 and Var2 for the x and y axes respectively:

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

I'd like to then reorder them by Culture, and then Coverage. However, if I try add more levels:

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

An error is thrown. Is there a way of adding more levels within the ggplot function call, rather then messing about with the data frame?

Z.Lin
  • 23,077
  • 5
  • 35
  • 71
user438383
  • 1,784
  • 1
  • 15
  • 24
  • Looking at the documentation for `reorder()`, I think it only takes a single "ordering" variable. So you are passing `Culture` to the `FUN` argument, which leads to the error message. A possible alternative would be to order your dataset according to all of the variables first and then do something like `forcats::fct_inorder()` to set the order of the levels. – aosmith Sep 14 '18 at 17:53
  • This is a possible workaround solution, since like @aosmith said, `reorder()` can only take one auxillary ordering vector. https://stackoverflow.com/questions/10758243/order-a-factor-based-on-value-in-one-or-more-other-columns – Anonymous coward Sep 14 '18 at 18:02

1 Answers1

0

am I missing something? maybe order() instead of reorder? :

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

enter image description here

In order to set the columns in the correct order set by the index -

Just use

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

enter image description here

But this seems somehow to simple, so I have the feeling that I might not have understood what you want :/

tjebo
  • 12,885
  • 4
  • 34
  • 61