【问题标题】:ggplot facet plot - change y-axis tick mark text using a patternggplot facet plot - 使用模式更改 y 轴刻度线文本
【发布时间】:2018-01-22 12:45:43
【问题描述】:

使用如下所示的数据框。

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()
  )

这给出了如下图。

我现在需要通过修剪标签中_ 之后的所有内容来替换 y 轴刻度线文本。我需要一种在 ggplot 中执行此操作的方法 - 而不是在原始数据帧 df 中。我希望我可以在 ggplot 中使用 gsub("[_].*$", "", x) 之类的东西 - 我该怎么做?

【问题讨论】:

    标签: r ggplot2


    【解决方案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(),而不是在每个几何图形中放置两次。否则transform() 也必须重复两次。

    【讨论】:

      【解决方案2】:

      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 函数;我发现它比使用基本字符串函数更方便、更清晰、更简洁,尤其是对于像标签这样的快速操作,但这只是一种偏好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多