0

So I'm new to R and already checked countless Stack Overflow threads and youtube videos but cant figure out how to do this simple taks. I have a stacked bar graph and wanted to labels on top of each bar for the various values counted.

Here's the basic code:

ggplot(data=cyclist_data2) +
  geom_bar(mapping = aes(x=member_casual, fill=rideable_type))

And the consequent graph:

enter image description here

I've tried adding a geom_text function that I saw in a video but it didn't work:

ggplot(data=cyclist_data2, mapping=aes(x=member_casual, y=rideable_type)) +
  geom_bar(stat = 'identity') +
  geom_text(aes(label = rideable_type), vjust = -0.2, colour = black, size = 5)

Help would be appreciated!

Esther
  • 356
  • 8
  • Please run `dput(cyclist_data2)` and paste the output into your question so others have a reproducible dataset to troubleshoot your question. – Shawn Hemelstrand Jan 23 '23 at 12:10
  • You could improve your chances of finding help here by adding a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). Adding a MRE and an example of the desired output (in code form, not tables and pictures) makes it much easier for others to find and test an answer to your question. That way you can help others to help you! P.S. Here is [a good overview on how to ask a good question](https://stackoverflow.com/help/how-to-ask) – dario Jan 23 '23 at 12:11

1 Answers1

0

If this is your data

df
# A tibble: 6 × 3
  grp   val     frq
  <chr> <chr> <dbl>
1 a     aw       10
2 a     dg        8
3 a     fg        6
4 b     aw        7
5 b     dg       10
6 b     fg        9

use geom_text to add the labels, position_stack gives you the right positions, and vjust lets you shift the labels up and down.

ggplot(df, aes(grp, frq, fill=val, label=frq)) + 
  geom_bar(stat="identity") + 
  geom_text(position = position_stack(vjust=0.5))

Note that you can replace geom_bar(stat="identity") with geom_col().

stacked bar plot

Data

df <- structure(list(grp = c("a", "a", "a", "b", "b", "b"), val = c("aw", 
"dg", "fg", "aw", "dg", "fg"), frq = c(10, 8, 6, 7, 10, 9)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -6L))
Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29