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?

2

2 Answers 2

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())
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.