首页 文章

ggplot facet plot - 使用模式更改y轴刻度标记文本

提问于
浏览
1

使用如下数据框 .

text <- "
name,var,value
tata_zest,a,99.8
toyota_prius,a,100.0
honda_civic,a,99.9
nissan_rx4,a,10 
tata_zest,b,8
toyota_prius,b,7
honda_civic,b,11
nissan_rx4,b,13
tata_zest,c,0.2
toyota_prius,c,0.21
honda_civic,c,0.15
nissan_rx4,c,0.32
tata_zest,d,300
toyota_prius,d,400
honda_civic,d,200
nissan_rx4,d,650
"
df <- read.table(textConnection(text), sep=",", header = T, stringsAsFactors = F)

我正在使用ggplot创建带有标签的条形图,如下所示 .

ggplot() +
geom_bar(
  data=df, color = "white", stat = "identity", position='dodge',
  aes(x=name, y=value)
) + coord_flip() +
geom_text(data = df, angle = 0, hjust = 1, 
          aes(x=name, y=value, label=value) 
          ) +
facet_wrap(~ var, scales = "free", ncol = 2) +
theme(
  axis.text.x=element_blank(),
  axis.title.y=element_blank()
  )

这给出了如下图 .

enter image description here

我现在需要通过修剪标签中的 _ 之后的所有内容来替换y轴刻度标记文本 . 我需要一种方法在ggplot中执行此操作 - 而不是在原始数据框 df 中 . 我希望我能在ggplot中使用像_1839669这样的东西 - 我该怎么做呢?

2 回答

  • 1

    您可以使用 transform()dplyr::mutate() 将更改版本的 df 传递给 ggplot() 而无需更改数据框:

    ggplot(data =  transform(df, name = sapply(strsplit(name, '_'), '[', 1))) +
      geom_bar(
        color = "white", stat = "identity", position='dodge',
        aes(x=name, y=value)
      ) + coord_flip() +
      geom_text(angle = 0, hjust = 1, 
                aes(x=name, y=value, label=value) 
      ) +
      facet_wrap(~ var, scales = "free", ncol = 2) +
      theme(
        axis.text.x=element_blank(),
        axis.title.y=element_blank()
      )
    

    请注意,我将 data = 参数移动到 ggplot() ,而不是在每个geom中都有两次 . 否则 transform() 也必须重复两次 .

  • 0

    scale_* 函数(例如本例中的 scale_x_discrete )具有接受函数的参数 labels . 您可以在其他地方定义函数并将其设置为 labels 参数,也可以定义函数内联 . 基础数据保持不变,但您更改标签的编写方式:

    ggplot(df, aes(x = name, y = value)) +
        geom_col(position = "dodge") +
        scale_x_discrete(labels = function(x) str_replace(x, "_.+$", "")) +
        coord_flip() +
        facet_wrap(~ var, scales = "free")
    

    请注意,我从 stringr 选择了 str_replace 函数;我发现它比使用基本字符串函数更方便,清晰,更简洁,特别是对于像标签这样快速的东西,但这只是一个偏好 .

相关问题