栏中间文字自动调整

问题描述 投票:0回答:3

我有一个名为 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))

导致:

enter image description here

如何将值(文本)自动放置在水平条的中间?

r dataframe ggplot2 geom-bar
3个回答
4
投票

您可以使用

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)
  )


4
投票

除以2:

ggplot(df, aes(x = var, y = val)) +
  geom_bar(stat = "identity", fill = "lightgrey") +
  geom_text(aes(x = var, y = val/2, label = val)) +
  coord_flip()

enter image description here


0
投票

在基地

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)) }
)

© www.soinside.com 2019 - 2024. All rights reserved.