0
votes

I have a sample of my original data frame called df and I'm trying to display the exact number of each bar on the bars.

I tried using the function geom_text(), but for using geom_text() I would need to define a y. But using geom_bar() doesn't require defining a y.

This is a sample of my dataframe:


df
    taet distance_km
   <dbl>       <dbl>
 1     4           4
 2     1           6
 3     2           5
 4     4           7
 5     4           3
 6     3           5
 7     1           5
 8     1           4
 9     2           4
10     1           2
11     1           1
12     4           6
13     1           4
14     1           7
15     1           2
16     4           7
17     1           4
18     4           4
19     1           6
20     2           9
21     1           5
22     4           4
23     1           1
24     1           6
25     1           3
26     1           3
27     5           2
28     1           2
29     1           8
30     1           3

This is my code for ggplot:


ggplot(df, aes(distance_km)) +
  theme_bw() +
  facet_wrap(~ taet) +
  geom_bar() +
  geom_text() +
  scale_x_continuous(limits = c(0,10), breaks = 1:9)

The shown data frame is only a little share of my original data frame. It is a lot harder to read/guess the exact number of each bar out of the diagram. I would like to display the exact number of each bar on the top of each bar, so the reader can easily identify the exact value of each bar.

1

1 Answers

0
votes

You need to include some extra arguments in geom_text. Below I have used geom_label, which adds a white background and I think might be clearer than geom_text in this case. You might want to add a size argument too, or you could use nudge_y to raise it above the top of the bar. See the help for geom_text for details of the various options.

ggplot(df, aes(distance_km)) +
  theme_bw() +
  facet_wrap(~ taet) +
  geom_bar() +
  geom_label(stat="count", aes(label=stat(count))) +  #or use geom_text here
  scale_x_continuous(limits = c(0,10), breaks = 1:9)

enter image description here