【问题标题】:Reorder ggplot axis by one value, display labels from another按一个值对 ggplot 轴重新排序,显示另一个值的标签
【发布时间】:2020-08-05 22:02:23
【问题描述】:

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

这在绘制数据时产生了一个问题,因为我在绘制时需要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 保持第二个图的显示和顺序,同时能够用第一个图的名称替换轴标签。

【问题讨论】:

    标签: r ggplot2 geom-bar


    【解决方案1】:

    如何使用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()
    

    是你要找的吗?

    【讨论】:

    • 是的,我想是的,花了一分钟时间解决,但这是我正在寻找的格式,谢谢!不幸的是,我实际的 name 条目包含标点符号,所以现在我需要查找如何从右到左删除直到第一个句点。
    猜你喜欢
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    相关资源
    最近更新 更多