按一个值重新排序 ggplot 轴,显示另一个标签

Reorder ggplot axis by one value, display labels from another

情况如下:
我有很多 names 和许多对应的 codes 这些名字。
所有不同的名称都有唯一的代码,但并非所有不同的代码都有唯一的名称。

这在绘制数据时产生了一个问题,因为我需要 group_by(code),并且在绘制时需要 reorder(name,code),但是代码是无意义的,我想显示名称。由于某些代码共享名称,因此会产生一些问题。

示例如下:

library(tidyverse)
set.seed(1)

# example df
df <- tibble("name" = c('apple','apple','pear','pear','pear',
                        'orange','banana','peach','pie','soda',
                        'pie','tie','beer','picnic','cigar'),
             "code" = seq(1,15),
             "value" = round(runif(15,0,100)))
df %>% 
  ggplot(aes(x=reorder(name,value)))+
  geom_bar(aes(y=value),
           stat='identity')+
  coord_flip()+
  ggtitle("The axis labels I want, but the order I don't")

df %>% 
  ggplot(aes(x=reorder(code,value)))+
  geom_bar(aes(y=value),
           stat='identity')+
  coord_flip()+
  ggtitle("The order I want, but the axis labels I don't")


不太确定如何让 ggplot 保持第二个图的显示和顺序,同时能够用第一个图中的名称替换轴标签。

如何使用 interaction 绑定名称和代码,并在 scale_x_discrete 中用适当的标签替换标签,例如:

df %>% 
  ggplot(aes(x=interaction(reorder(name, value),reorder(code,value))))+
  geom_bar(aes(y=value),
             stat='identity')+
  scale_x_discrete(labels = function(x) sub("\..*$","",x), name = "name")+
  coord_flip()

是您要找的吗?