14

Here is my simple assets dataset:

ID  Type    Currency    Value
a   Bond    GBP         10
b   Bond    EUR         20
c   Stock   GBP         3
d   Stock   GBP         60
e   Bond    GBP         8
f   Bond    USD         39
g   Stock   USD         1

Here is the code:

 assets <- read_excel("C:/R/SampleData.xlsx")
 g <- ggplot(assets, aes(Currency, Value))
 g + geom_col()

And this is the plot that I get:

bar plot

I am trying to create the same plot, but with bars sorted by value (in descending order) How do I achieve this? I have tried the following code:

assets$Currency <- factor(assets$Currency, levels = assets$Currency[order(assets$Value)])

But I get the following warning message and the chart is still not sorted correctly:

Warning message:
In `levels<-`(`*tmp*`, value = if (nl == nL) as.character(labels) else paste0(labels,  :
duplicated levels in factors are deprecated

Thanks!

MrFlick
  • 195,160
  • 17
  • 277
  • 295
F. F.
  • 141
  • 1
  • 1
  • 3

1 Answers1

20
  ggplot(assets, aes(reorder(Currency, -Value, sum), Value)) +
  geom_col()

enter image description here

yeedle
  • 4,918
  • 1
  • 22
  • 22
  • 1
    By default `reorder` works based on the `mean` of the observations. If you want to sort by total bar height, you need to explicitly set the function to `sum` – MrFlick Apr 13 '17 at 16:49
  • You're right. I edited to reflect that – yeedle Apr 13 '17 at 16:49