【问题标题】:ggplot: modify axis labels with named vector after having applied functionggplot:在应用函数后用命名向量修改轴标签
【发布时间】:2021-10-01 11:06:09
【问题描述】:

我有一个关于在 ggplot 中修改轴标签的问题。我知道我想要达到的目的可以通过其他方式完成(例如,使用case_when 创建一个新列)。我的兴趣在于下面概述的方法/概念。

假设我在 x 轴上有一个离散变量。为了获得所需的轴标签,值是 1) 使用函数修改的,然后 2) 通过将命名向量中包含的值分配给函数的结果来更改。我能够单独完成这两个步骤中的每一个;但是它们如何结合起来呢?这个可以吗?

再次,我知道还有其他可能更理智的方法可以做到这一点。下面的例子没有任何实质性意义。我只是好奇是否/如何可以直接在例如scales_x_discrete 函数。下面我试图详细说明我的意思。结果将是所有Merc 标签变为Mercedes,所有Hornet 实例变为Super Hornet

library(tidyverse)

labeller_cars <- c("Hornet"="Super Hornet",
                   "Merc"="Mercedes")

mtcars %>% 
  rownames_to_column(var = "name") %>% 
  filter(str_detect(name, regex("Hornet|Merc"))) %>% 
  ggplot()+
  geom_bar(aes(x=name,
               y=disp),
           stat="identity")+
  #here is what I am interested in; this works, but it's only first step
  scale_x_discrete(labels=function(x) str_extract(x, regex("[:alpha:]*")))
  #this is an attempt, but doesn't work.
  # scale_x_discrete(labels=function(x) str_extract(x, regex("[:alpha:]*")) %>% labeller_cars)

reprex package (v2.0.0) 于 2021 年 7 月 24 日创建

【问题讨论】:

    标签: r ggplot2 axis-labels


    【解决方案1】:

    我们可以使用str_replace_all 代替str_extract

    library(dplyr)
    library(stringr)
    library(ggplot2)
    labeller_cars <- c(".*Hornet.*"="Super Hornet",
                        ".*Merc.*"="Mercedes")
    mtcars %>% 
       rownames_to_column(var = "name") %>% 
       filter(str_detect(name, regex("Hornet|Merc"))) %>% 
       ggplot()+
       geom_bar(aes(x=name,
                    y=disp),
                stat="identity")+
       #here is what I am interested in; this works, but it's only first step
       scale_x_discrete(labels=function(x) str_replace_all(x, labeller_cars)) + 
     theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
    

    -输出


    或者用str_extract,提取子串后,使用命名向量进行匹配替换

    labeller_cars <- c("Hornet"="Super Hornet",
                        "Merc"="Mercedes")
    mtcars %>% 
       rownames_to_column(var = "name") %>% 
       filter(str_detect(name, regex("Hornet|Merc"))) %>% 
       ggplot()+
       geom_bar(aes(x=name,
                    y=disp),
                stat="identity")+
       scale_x_discrete(labels=function(x)
          labeller_cars[str_extract(x, regex("[:alpha:]*"))])
    

    -输出

    【讨论】:

    • 非常感谢。我意识到我的示例不是很好,因为预期的结果是 2 列将被称为“超级大黄蜂”,而所有其他列将被称为“梅赛德斯”。我感兴趣的是在对标签应用函数之后通过命名向量修改标签(这里 - str_extract,它将所有黄蜂队和 Merc 集中在一起)。 ——
    • 非常感谢您的回复,如果我不够清楚,我们深表歉意。 str_extract ì 在我的示例中产生了多个 Hornet 和 Merc(因为它只从标签中提取了这一部分)。这是第一步。现在我想将这些结果与命名向量匹配(?)以获得最终标签。函数 str_extract 在这里仅用作示例。我感兴趣的一点是如何使用函数的结果(在 scale_x_discrete(labels=...) 中使用以匹配命名向量。我使用使用 str_remove 等的示例。我假设我以某种方式必须把它整合到我的 fn 中。
    • 第二种解决方案是我正在寻找的。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多