【问题标题】:How to display the values of every single bar in a barplot in R (without using ggplot)?如何在 R 中的条形图中显示每个条形的值(不使用 ggplot)?
【发布时间】:2021-11-20 12:19:08
【问题描述】:

我是 R 的初学者,感谢到目前为止提供的帮助,我设法使用下面的代码创建了以下 Barplot。但是,有一个问题仍然悬而未决,即使在阅读了类似问题中提供的所有答案之后,我也无法解决它。

代码:

res <- data.frame( aggregate( rentals ~ weatherCond + season, bikes, sum ))

res$weatherCond <- ordered(res$weatherCond,
levels = c(1, 2, 3, 4),
labels = c("Clear", "Fog", "Snow", "Storm"))

res$season <- factor(res$season,
levels = c(1, 2, 3, 4),
labels = c("Winter", "Spring", "Summer", "Autumn"))

par(mar=c(10,4,2,1)+.5) 
barplot(res[,"rentals"], names=apply( res[,1:2], 1, function(x) paste0(x[1],"_",x[2]) ), las=3, main = "Weather and Rentals", ylab = "Rentals", col = c('blue', 'red', 'green', 'grey')[res$weatherCond])

该图可视化了租用自行车数量与季节之间的联系,具体取决于天气条件(3 个变量)。图中的条形显示了租用的自行车数量,分为相应的季节/天气组合。

我的问题: 我应该如何修改上面的代码,以便可以显示每个条的值的计数(在条中或条的顶部)?每个条形代表出租的数量。

更新: 我设法通过添加以下代码行来显示这些值:

y <- as.matrix(res$rentals)
text(b, y+2, labels=as.character(y)) <!-- the "b" is the barplot -->

然而,结果是可怕的。有没有办法让它看起来更好?

【问题讨论】:

  • 您应该修改您的 ylim 设置,请参阅下面的示例。您还可以旋转数字使它们更小(text() 中的参数 cex)。

标签: r bar-chart


【解决方案1】:

barplot() 返回每​​个柱的中点(请参阅?barplot)。这可以与函数text()结合使用来显示数字。

你的情况,它会变成:

mid_points <- barplot(res[,"rentals"], ...)
text(x = mid_points, y = res[,"rentals"], text = res[,"rentals"])

更多参数可用于修改数字的位置。 由于我没有你的数据,我使用了一个修改过的基础 R 示例:

b <- barplot(GNP ~ Year, data = longley, ylim = c(0, 700))
text(
  x = b,
  y = longley$GNP,
  labels = round(longley$GNP, 1),
  pos = 3,
  srt = 90,
  offset = 1.5
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    相关资源
    最近更新 更多