如何使用R ggplot按值对条形图进行排序?

时间:2017-04-13 16:39:30

标签: r ggplot2

这是我的简单资产数据集:

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

以下是代码:

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

这是我得到的情节:

bar plot

我正在尝试创建相同的绘图,但是按值排序的条形图(按降序排列) 我该如何实现这一目标? 我尝试了以下代码:

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

但是我收到以下警告消息,图表仍未正确排序:

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

谢谢!

1 个答案:

答案 0 :(得分:1)

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

enter image description here