ggplot:在应用函数后使用命名向量修改轴标签

问题描述

我有一个关于修改 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 日创建

解决方法

我们可以使用 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))

-输出

enter image description here


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

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

-输出

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...