2

I'd like to reproduce the following base barplot, using ggplot2::geom_bar().

Toy data :

set.seed(314)
dat <- data.frame("Player" = rep(c("P1", "P2", "P3", "P4", "P5"), times = 2),
                  "Score" = runif(n = 10, 0, 10) * 3)

base barplot : the variable Player is duplicated

barplot(height = dat$Score, names.arg = dat$Player)

barplot_1

geom_bar : the variable Player is grouped

ggplot(dat) +
  geom_bar(aes(x = Player, y = Score), stat = "identity")

barplot_2

How to use geom_bar() so that the variable is duplicated (and not grouped) ? What am I missing ?

EDIT :
I changed the code of the base barplot to reorder the data and make more explicit the difference between the 2 functions : I am not sure that the following plot is reproducible using ggplot2 (without any tricks on the data itself).

barplot(height = dat[order(dat$Score, decreasing = TRUE), "Score"],
        names.arg = dat[order(dat$Score, decreasing = TRUE), "Player"])

barplot_3

i94pxoe
  • 577
  • 3
  • 11
  • Not exactly the same as in the base plot but you can try `ggplot(dat) + geom_col(aes(x = Player, y = Score), position = "dodge2")` Note that `geom_col()` is the same as `geom_bar(..., stat = "identity")` – markus Feb 22 '19 at 08:40
  • thanks. indeed not exactly the same, but it is a start. Noted for `geom_col()`, nice shortcut. – i94pxoe Feb 22 '19 at 08:44
  • 2
    `dat %>% mutate(Player2 = paste0(Player, 1:10)) %>% ggplot() + geom_bar(aes(x = Player2, y = Score), stat="identity")` possibly this, but I suspect that it chages the order of bars. – RLave Feb 22 '19 at 09:11
  • `Player2` is different across each observations. – RLave Feb 22 '19 at 09:12
  • @RLave Nice trick. Using this, I can add another column and reorder the bars : `dat %>% mutate(Player2 = paste0(Player, 1:10), ord = 1:10) %>% ggplot(aes(x = reorder(Player2, ord), y = Score)) + geom_col() + scale_x_discrete(labels = dat$Player)`. But that's a lot of tricks... I wonder if there is something less cumbersome... – i94pxoe Feb 22 '19 at 10:26
  • Can you elaborate *why* you'd want to achieve this? What's the use case? – Z.Lin Feb 22 '19 at 14:14
  • no specific usecase in mind (for now). I was just playing around with `geom_bar()` and was very intrigued that I could not reproduce a very simple base barplot... – i94pxoe Feb 22 '19 at 15:19

0 Answers0