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

时间:2019-11-24 18:48:11

标签: r ggplot2 dplyr pipeline

有没有办法在同一管道中使用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))

基本上,我是在计算其他作者(因子列)出现在数据框中的次数。但是,R不允许我在scale_x_continuous中使用n(即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))

谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用花括号和点表示法(this questionhere中接受的答案的最后一部分中的相关信息):

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

reprex package(v0.3.0)于2019-11-24创建

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