简体   繁体   中英

How to display individual bar values using ggplot() + geom_bar() without specifying y values

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.

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)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM