[英]How to add count labels in ggplot2 barplot?
我正在尝试将计数标签放在 ggplot2 barplot 中,但我无法做到。 我需要显示每个温度范围内的像素数。 数据框是从栅格构建的:EneroT5cmSC
datene <- as.data.frame(EneroT5cmSC,xy=TRUE)%>%drop_na()
datene$cuts <- cut(datene$layer, breaks=seq(21, 29, length.out=12))
输入:
datene_stuc <- structure(
list(
x = c(-57.063098328,-57.021448328,-56.996458328,-56.988128328),
y = c(-30.087481664,-30.087481664,-30.087481664,-30.087481664),
layer = c(
25.6227328470624,
26.6386584334308,
26.0636709134397,
26.0580615984563
),
cuts = structure(
c(7L, 9L,
8L, 8L),
.Label = c(
"(20,20.8]",
"(20.8,21.6]",
"(21.6,22.5]",
"(22.5,23.3]",
"(23.3,24.1]",
"(24.1,24.9]",
"(24.9,25.7]",
"(25.7,26.5]",
"(26.5,27.4]",
"(27.4,28.2]",
"(28.2,29]"
),
class = "factor"
)
),
row.names = c(NA,
4L),
class = "data.frame")
条形图代码:
ggplot() +
geom_bar(data = datene, aes(cuts, fill = cuts)) +
scale_fill_viridis_d(option = "B",'Temp (Cº)') +
theme(axis.title.x=element_blank(), axis.title.y=element_blank()) +
geom_text(aes(label = ..count..), stat = "count", vjust = 1.5, colour = "black")
如果您将代码参数从geom_bar
替换为ggplot()
并更改vjust = -1
它的工作方式如下:
datene_stuc <- structure(
list(
x = c(-57.063098328,-57.021448328,-56.996458328,-56.988128328),
y = c(-30.087481664,-30.087481664,-30.087481664,-30.087481664),
layer = c(
25.6227328470624,
26.6386584334308,
26.0636709134397,
26.0580615984563
),
cuts = structure(
c(7L, 9L,
8L, 8L),
.Label = c(
"(20,20.8]",
"(20.8,21.6]",
"(21.6,22.5]",
"(22.5,23.3]",
"(23.3,24.1]",
"(24.1,24.9]",
"(24.9,25.7]",
"(25.7,26.5]",
"(26.5,27.4]",
"(27.4,28.2]",
"(28.2,29]"
),
class = "factor"
)
),
row.names = c(NA,
4L),
class = "data.frame")
library(ggplot2)
ggplot(data = datene_stuc, aes(cuts, fill = cuts)) +
geom_bar() +
geom_text(aes(label = ..count..), stat = "count", vjust = -1, colour = "black") +
scale_fill_viridis_d(option = "B",'Temp (Cº)') +
theme(axis.title.x=element_blank(), axis.title.y=element_blank())
由reprex 包于 2022-07-17 创建 (v2.0.1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.