dplyr + ggplot2。在同一管道内的 scale_x_continuous() 中使用使用 dplyr 计算的列

pib*_*o95 0 pipeline r ggplot2 dplyr

有没有办法在同一管道中使用 ggplot2 的 scale_x_continuous() 中使用 dplyr 计算的列?

p2 <- chat %>%
        count(author) %>%
        ggplot(aes(x = reorder(author, n), y = n, fill = n)) +
          geom_bar(stat = "identity") +
          coord_flip() +
          theme_classic() +
          scale_fill_viridis() +
          scale_x_continuous(breaks = seq(0, **max(n)**, by = 250))
          theme(
            axis.title.x = element_blank(), axis.title.y = element_blank(),
            legend.position = "none",
            plot.title = element_text(size = 13, face = "bold", hjust = 0.5),
            plot.subtitle = element_text(color = '#666664', size = 10, hjust = 0.5))
Run Code Online (Sandbox Code Playgroud)

基本上,我正在计算不同作者(因子列)出现在数据框中的次数。但是,R 不允许我使用n在 scale_x_continuous 中(这是 count() 返回的列的名称)。但它确实在 ggplot() 函数中。

有没有办法这样做?或者我被迫做这样的事情:

data <- chat %>%
        count(author)

p2 <- ggplot(data, aes(x = reorder(author, n), y = n, fill = n)) +
          geom_bar(stat = "identity") +
          coord_flip() +
          theme_classic() +
          scale_fill_viridis() +
          scale_x_continuous(breaks = seq(0, **max(data$n)**, by = 250))
          theme(
            axis.title.x = element_blank(), axis.title.y = element_blank(),
            legend.position = "none",
            plot.title = element_text(size = 13, face = "bold", hjust = 0.5),
            plot.subtitle = element_text(color = '#666664', size = 10, hjust = 0.5))
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Mal*_*udo 5

您可以使用花括号和点符号(此问题此处接受的答案的最后一部分中的相关信息):

library(tidyverse)
library(viridis)
#> Loading required package: viridisLite
p2 <- iris %>%
  sample_n(100) %>% 
  count(Species) %>%
  {
    ggplot(., aes(x = reorder(Species, n), y = n, fill = n)) +
      geom_bar(stat = "identity") +
      coord_flip() +
      theme_classic() +
      scale_fill_viridis() +
      scale_y_continuous(breaks = seq(0, max(.$n), by = 20)) +
      theme(
        axis.title.x = element_blank(), axis.title.y = element_blank(),
        legend.position = "none",
        plot.title = element_text(size = 13, face = "bold", hjust = 0.5),
        plot.subtitle = element_text(color = '#666664', size = 10, hjust = 0.5)
      )
  }
p2
Run Code Online (Sandbox Code Playgroud)

reprex 包(v0.3.0)于 2019 年 11 月 24 日创建

请注意,您没有提供任何可重复的示例,因此我将其iris作为起点并进行了一些行采样,以获得物种计数的不同频率。如果您使用可重现的示例更新您的问题,我将更新我的答案。