3

The following R snippet

library(ggplot2)
library(reshape2)

data <- data.frame(
          item  = c('foo', 'bar', 'baz'),
          val_1 = c(   7 ,    9 ,    3 ),
          val_2 = c(   1 ,    2 ,    3 )
        );

data

data$tot = data$val_1 + data$val_2;

data.molten = melt(data);

ggplot(
   data = data.molten,
   aes(x = variable, y = item ))  +
   geom_tile(aes(fill  = value))  +
   geom_text(aes(label = value))

produces

enter image description here

Is there a possibility to have it ordered by the value of tot descending so that row with bar is at the top and baz is at the bottom.

René Nyffenegger
  • 39,402
  • 33
  • 158
  • 293

2 Answers2

6

Add this line:

data$item <- reorder(data$item,data$tot)

before melting.

The canonical StackOverflow question on this topic is here and the answer is basically always "set the factor levels in the desired order", but how you do that in practice can vary from case to case in ways that are a little beyond the scope of a single StackOverflow answer.

joran
  • 169,992
  • 32
  • 429
  • 468
0

you could use reorder() within your aes() in ggplot().

Something like this...

    ggplot(
       data = data.molten,
       aes(x = variable, y = reorder(item, value), fill = value)  +
       geom_tile()+
       geom_text(aes(label = value))
Martin Gal
  • 16,640
  • 5
  • 21
  • 39