![](/img/trans.png)
[英]How to add y axis values on the bar plot in r using ggplot and geom_bar()?
[英]How to display individual bar values using ggplot() + geom_bar() without specifying y values
我有一个名为 df 的原始数据框样本,我试图在条形图上显示每个条形的确切数量。
我尝试使用 function geom_text(),但对于使用 geom_text(),我需要定义一个 y。 但是使用 geom_bar() 不需要定义 y。
这是我的 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
这是我的 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)
显示的数据框只是我原始数据框的一小部分。 阅读/猜测图表中每个条的确切数量要困难得多。 我想在每个条的顶部显示每个条的确切数量,以便读者可以轻松识别每个条的确切值。
您需要在 geom_text 中包含一些额外的geom_text
。 下面我使用了geom_label
,它添加了一个白色背景,我认为在这种情况下可能比geom_text
更清晰。 您可能还想添加一个size
参数,或者您可以使用nudge_y
将其提升到条形顶部上方。 有关各种选项的详细信息,请参阅geom_text
的帮助。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.