Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何通过另一个变量设置图例顺序?_R_Ggplot2_Data.table - Fatal编程技术网

R 如何通过另一个变量设置图例顺序?

R 如何通过另一个变量设置图例顺序?,r,ggplot2,data.table,R,Ggplot2,Data.table,我想按名称级别绘制以下数据集: time <- 1:3 qty <- 1:10 ugly_name <- c("ii" , "aaa" , "oNe", "iv" ) nice_name <- c("Two", "Three", "One", "Four") dt <- data.table(time,

我想按名称级别绘制以下数据集:

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


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

forcats::fct\u reorder允许您将
丑陋的\u名称
的顺序应用于
新的\u名称
。在本例中,我需要将
包装为.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_重新排序的情况下使用另一个变量的级别来考虑一个变量,但我无法做到。
ggplot(dt, aes(x = time, y = qty, 
               fill = nice_name %>% forcats::fct_reorder(as.numeric(ugly_name)))) + 
  geom_col() +
  scale_fill_discrete(name = "category")