我有一个名为 df 的数据框:
df = tibble(var =c("A","B","C","D","E"), val = c(2,8,9,1,5) );df
导致:
var val
<chr> <dbl>
1 A 2
2 B 8
3 C 9
4 D 1
5 E 5
我想水平绘制 val 列的条形图,并将每个类别的值以文本形式绘制在条形图中间。
ggplot(df, aes(x = var, y = val)) +
geom_bar(stat = "identity", fill = "lightgrey") +
coord_flip() + # This flips the coordinates to make the bars horizontal
geom_text(aes(label = val))
导致:
如何将值(文本)自动放置在水平条的中间?
您可以使用
position = position_stack(vjust = .5)
将标签放入条形中间:
library(ggplot2)
ggplot(df, aes(x = val, y = var)) +
geom_bar(
stat = "identity",
fill = "lightgrey"
) +
geom_text(
aes(label = val),
position = position_stack(vjust = .5)
)
在基地
X = data.frame(var =c("A","B","C","D","E"), val = c(2,8,9,1,5))
with(X, {
barplot(val, horiz=TRUE, names.arg=var, las=2L, xaxt="n") |>
text(x=val/2L, labels=val)
axis(side=1L, at=seq(0L, max(X$val), 2.5)) }
)