【问题标题】:Can I show percentage of bars using barplot()?我可以使用 barplot() 显示条形的百分比吗?
【发布时间】:2021-03-09 08:00:59
【问题描述】:

我正在尝试在我的 barplot() 顶部添加百分比。

我一直在寻找并发现使用 ggplot 可以做到这一点,但我正在使用 barplot() 执行此操作,但我找不到方法。我试过 label.bars,但显然它不是这个函数的一部分。

这是我的代码:

barplot(table(marriage$year, marriage$dummy) , 
  beside=T, ylab="Frequency", 
  main="Distribution of Opposition and Support on Marriage Equality", 
  col= c("lightblue" , "lightgreen"), 
  names.arg=(c("1988", "2010")) , 
  legend.text = c("Support", "Oppose"), 
  ylim = c(0, 1000))

有什么想法吗?

谢谢!

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。
  • 谢谢@MrFlick,但是,我还没有找到可以做我想做的事情的代码,所以我没有任何示例。我找到了很多 ggplot2 的示例,但没有一个使用基本函数 barplot() 的示例。我会继续寻找。谢谢你的建议。
  • 如果您没有代码也没关系,但您应该能够包含我们可以复制/粘贴到 R 中进行测试的示例数据。为marriage 提供示例值,这样我们就不必自己编造它们来测试可能的解决方案。它使帮助您变得更加容易。

标签: r plot bar-chart


【解决方案1】:

table 输出存储在对象中(此处为tab)以及不可见的barplot 输出(此处为b)。然后使用proportions 将其放入text。很简单:)

b <- barplot(tab <- table(mtcars$vs, mtcars$am), 
        beside=T, ylab="Frequency", 
        main="Distribution of Opposition and Support on Marriage Equality", 
        col= c("lightblue" , "lightgreen"), 
        names.arg=(c("1988", "2010")) , 
        legend.text = c("Support", "Oppose"),
        ylim=c(0, 15))
text(x=b, y=tab + .8, labels=paste0(round(proportions(tab), 1), "%"))

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 2011-03-28
    • 1970-01-01
    • 2019-02-04
    • 2017-09-15
    相关资源
    最近更新 更多