1

I'm tryng to do a bar plot with percentages instead of counts, and I've tried this:

ggplot(data = newdf3) + 
  geom_bar(mapping = aes(x = key, y = ..prop..,fill=value,group = 1), stat = "count",position=position_dodge()) + 
  scale_y_continuous(labels = scales::percent_format())

but apparently "group=1" is not working because this is what it returns: graf1

and if I don't use "group=1" it returns: graf2

here's a sample of data I'm using:

key   value

1     Before
1     After
1     During
1     Before
2     Before
2     After
3     During
...


Can someone help me with this?

  • I've added the exemple – user11579557 Oct 28 '19 at 23:40
  • 1
    Hi! I'm not really clear, on what you're trying to achieve. Maybe you find an example of a similar plot in here? https://ggplot2.tidyverse.org/reference/position_stack.html Please also have a look here: https://stackoverflow.com/a/5963610/1842673 – TobiO Oct 28 '19 at 23:57

2 Answers2

1

Consider using geom_col() instead of geom_bar().

However, you should be able to get around your problem with stat="identity".

library(ggplot2)

#sample data.frame
df <- data.frame(
  group = c("A","A","B","B","C","C"),
  value = c(0.1,0.5,0.3,0.1,0.2,0.6)
)
df %>% head

#histogram
df %>% 
  ggplot(aes(x = group)) + 
  geom_bar()

#NOT histogram
df %>% 
  ggplot(aes(x = group, y = value)) + 
  geom_bar(stat = "identity") +
  scale_y_continuous(labels = scales::percent_format())
0

One solution would be to calculate relative frequency with you input data and pass the results directly to ggplot, using the stat = "identity" parameter in geom_bar (see this post):

library(tidyverse)

df <- tibble::tribble(
  ~key, ~value,
  1, "Before",
  1, "After",
  1, "During",
  1, "Before",
  2, "Before",
  2, "After",
  3, "During"
)

df %>%
  dplyr::count(key, value) %>%
  dplyr::group_by(key) %>%
  dplyr::mutate(p = n / sum(n)) %>%
  ggplot() + 
    geom_bar(
      mapping = aes(x = key, y = p, fill = value),
      stat = "identity",
      position = position_dodge()
    ) + 
    scale_y_continuous(labels = scales::percent_format())

Created on 2019-10-28 by the reprex package (v0.3.0)

sboysel
  • 631
  • 7
  • 17