0

Is there a way to use a column calculated with dplyr in scale_x_continuous() from ggplot2 in the same pipeline?

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

Basically, I'm counting the number of times a different author (factor column) appears in the dataframe. However, R is not letting me use n (which is then name of the column that count() returns) in scale_x_continuous. But it does within the ggplot() function.

Is there a way to do so? Or am I forced to do something like:

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

Thanks in advance!

piblo95
  • 123
  • 1
  • 2
  • 10

1 Answers1

5

You can use curly braces and dot notation (relevant information in last part of the accepted answer in this question, and here):

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

Created on 2019-11-24 by the reprex package (v0.3.0)

Please note that you did not provide any reproducible example, so I took iris as starting point and did some row sampling to get different frequencies for the Species count. If you update your question with a reproducible example I will update my answer.

MalditoBarbudo
  • 1,815
  • 12
  • 18