【问题标题】:How can I write a function for ggplot2's scale in a dplyr workflow?如何在 dplyr 工作流程中为 ggplot2 的比例编写函数?
【发布时间】:2020-07-10 11:23:12
【问题描述】:

我想在一个管道工作流中动态设置ggplot2::scale_x_discrete()(或类似)中的标签,由于我失败了,我似乎对管道的工作方式有误解。我在下面的两个示例中说明了我的问题,示例 1 可以正常工作,示例 2 是我编写代码的理想方式。我想一次性操作变异变量的标签。

library(dplyr)
library(ggplot2)

以下是有效的。如您所见,我可以通过引用中间data.frame df来操纵disp的级别

# Example 1
df <- 
  mtcars %>% 
  mutate(disp = cut(disp, breaks = 5)) 

df %>%   
  ggplot(aes(disp, hp)) +
  geom_point() + 
  scale_x_discrete(labels = substring(levels(df$disp), 2, 4))

但是我想写的是下面的东西(不起作用)

# Example 2
mtcars %>% 
  mutate(disp = cut(disp, breaks = 5)) %>%
  ggplot(aes(disp, hp)) +
  geom_point() + 
  scale_x_discrete(labels = substring(levels(.data$disp), 2, 4))

我需要写什么而不是.data$disp

【问题讨论】:

    标签: r ggplot2 dplyr


    【解决方案1】:

    你可以用大括号把整个ggplot变成一个表达式

    mtcars %>% 
      mutate(disp = cut(disp, breaks = 5)) %>%
      {
        ggplot(data = ., aes(disp, hp)) +
        geom_point() + 
        scale_x_discrete(labels = substring(levels(.$disp), 2, 4))
      }
    

    然后您可以将数据始终称为.

    【讨论】:

      【解决方案2】:

      您可以将函数传递给labels 参数:

      library(dplyr)
      library(ggplot2)
      
      mtcars %>% 
        mutate(disp = cut(disp, breaks = 5)) %>%
        ggplot() + aes(disp, hp) + 
        geom_point() + 
        scale_x_discrete(labels = function(x) substring(x, 2, 4))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-06
        • 2018-03-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多