【问题标题】:Text in barplot in RR中条形图中的文本
【发布时间】:2018-11-03 19:12:11
【问题描述】:

在 R 的条形图中添加值时遇到问题。问题是我无法将值放在每个条形的中间

balance<- c(-4.3963714,0.2335795,-0.2777250,-2.0037130,-1.2526801, -6.4556516)
barnames<-c("E1","E11","E12","E5","E7","E9")
barplot(balance,ylim=c(-8,2),col=c(if ((balance[1])>0) "blue"  else "red",(if ((balance[2])>0) "blue"  else "red"),(if ((balance[3])>0) "blue"  else "red"), (if ((balance[4])>0) "blue"  else "red"),(if ((balance[5])>0) "blue"  else "red"), (if ((balance[6])>0) "blue"  else "red")),main="Balance del Stock de Carbono",names.arg= barnames,ylab="Variacion del Stock de C kg/m2")    
abline(h=0)
text((balance/2),labels=round(balance,digits=2))

这是条形图:

【问题讨论】:

  • 我的建议是研究 ?barplot 及其 Values 部分,然后运行示例。

标签: r text bar-chart


【解决方案1】:

您只需保存由barplot 返回的条形的 x 位置。

您还可以使col 参数更简单。使用ifelseif 的矢量化版本。

bp <- barplot(balance, ylim = c(-8, 2), 
              col = ifelse(balance > 0, "blue", "red"),
              main = "Balance del Stock de Carbono",
              names.arg = barnames,
              ylab="Variacion del Stock de C kg/m2")

abline(h=0)
text(bp, balance/2, labels = round(balance, digits = 2))

【讨论】:

    【解决方案2】:

    如果你不介意使用ggplot2,你可以让标签看起来更漂亮一点

    library(tidyverse)
    
    tibble(barnames, balance) %>% 
      mutate(lab_loc = balance/2
             , col = factor(sign(balance))) %>% 
      ggplot(aes(x = barnames, y = balance)) +
        geom_col(aes(fill = col)) +
        geom_label(aes(y = lab_loc, label = round(balance, 2))) +
        scale_fill_manual(name = 'sign', values = c('1' = 'blue', '-1' = 'red')) +
        ylab('Variacion del Stock de C kg/m2') +
        ggtitle('Balance del Stock de Carbono') +
        theme(plot.title = element_text(hjust = 0.5))
    

    【讨论】:

      猜你喜欢
      • 2014-07-22
      • 2015-04-10
      • 2020-12-22
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 2015-01-22
      • 2013-03-22
      相关资源
      最近更新 更多