【问题标题】:How do I set the legend order by another variable?如何通过另一个变量设置图例顺序?
【发布时间】:2021-03-15 23:23:11
【问题描述】:

我想绘制按丑陋名称级别排序的以下数据集:

time <- 1:3
qty <- 1:10
ugly_name <- c("ii" , "aaa"  , "oNe", "iv"  )
nice_name <- c("Two", "Three", "One", "Four")

dt <- data.table(time, qty, ugly_name,nice_name)
dt[, ugly_name := factor(ugly_name, levels = c("oNe", "ii" , "aaa"  , "iv"  ))]
ggplot(dt, aes(x = time, y = qty, fill = ugly_name)) + geom_col()

但是我想将图例中的ugly_name 更改为nice_name

我得到它的繁琐方式是:

dt2 <- dt[, .(ugly_name, nice_name)] %>% unique()
dt2 <- dt2[order(ugly_name)]
dt[, nice_name:= factor(nice_name, levels = dt2$nice_name)]
ggplot(dt, aes(x = time, y = qty, fill = nice_name)) + 
  geom_col()

有没有更直接的方法来完成它,最好是在 ggplot 中?

【问题讨论】:

    标签: r ggplot2 data.table


    【解决方案1】:

    forcats::fct_reorder 允许您将ugly_name 的排序应用于new_name。在这种情况下,我需要在 as.numeric() 中换行,但不完全确定原因。

    ggplot(dt, aes(x = time, y = qty, 
                   fill = nice_name %>% forcats::fct_reorder(as.numeric(ugly_name)))) + 
      geom_col() +
      scale_fill_discrete(name = "category")
    

    【讨论】:

    • 使用一个新的包只是为了重新排序听起来不是一个好主意
    • 您有什么建议吗?我试图在没有 fct_reorder 的情况下使用另一个变量的级别来分解一个变量,但我做不到。
    猜你喜欢
    • 2020-09-14
    • 1970-01-01
    • 2018-03-16
    • 2018-07-25
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多