【问题标题】:how to add labels above the bar of "barplot" graphics?如何在“barplot”图形的栏上方添加标签?
【发布时间】:2025-12-09 20:05:01
【问题描述】:

我之前问过一个问题,但现在我想知道如何将标签放在条形上方。

旧帖:how to create a frequency histogram with predefined non-uniform intervals?

dataframe <- c (1,1.2,40,1000,36.66,400.55,100,99,2,1500,333.45,25,125.66,141,5,87,123.2,61,93,85,40,205,208.9)

更新

更新

按照同事的指导,我正在更新问题。

我有一个数据库,我想计算该碱基的给定值出现在预定义范围内的频率,例如:0-50、50-150、150-500、500-2000。

在帖子中(how to create a frequency histogram with predefined non-uniform intervals?) 我设法做到了,但我不知道如何在条形上方添加标签。我试过了:

barplort (data, labels = labels),但是没用。

我使用 barplot 是因为帖子推荐了我,但如果可以使用 ggplot 来做,那也很好。

【问题讨论】:

  • this question的答案有帮助吗?
  • 与R Studio IDE无关的帖子请不要标记rstudio
  • 如果@eipi10 链接的问题没有帮助,请添加更多详细信息和可重现的可视化示例(所以这个问题是独立的)
  • @stragu 我编辑了问题

标签: r


【解决方案1】:

基于the answer to your first question,这是将text() 元素添加到Base R 图的一种方法,该元素用作每个条形图的标签(假设您想将已经存在的信息加倍)在 x 轴上)。

data <- c(1,1.2,40,1000,36.66,400.55,100,99,2,1500,333.45,25,125.66,141,5,87,123.2,61,93,85,40,205,208.9)
# Cut your data into categories using your breaks
data <- cut(data, 
            breaks = c(0, 50, 150, 500, 2000),
            labels = c('0-50', '50-150', '150-500', '500-2000'))
# Make a data table (i.e. a frequency count)
data <- table(data)
# Plot with `barplot`, making enough space for the labels
p <- barplot(data, ylim = c(0, max(data) + 1))
# Add the labels with some offset to be above the bar
text(x = p, y = data + 0.5, labels = names(data))

如果是您所追求的 y 值,您可以更改传递给 labels 参数的内容:

p <- barplot(data, ylim = c(0, max(data) + 1))
text(x = p, y = data + 0.5, labels = data)

reprex package (v0.3.0) 于 2020 年 12 月 11 日创建

【讨论】: