r - 将标签放在负和正 geom_bar 上

标签 r ggplot2 geom-bar geom-text

我想使用条形图和 ggplot 可视化数据.

我有下面的数据,当我想查看这些数据时,负值的文本没有显示在 Bar 下方。

dat <- read.table(text = "sample Types Value
sample1 A   -36
sample2 B   31
sample1 C   15
sample2 D   -12
sample1 E   27
sample2 F  16
sample2 G  -10
sample2 H  2
sample2 I  6
sample2 J  -7
sample2 K  -8"
, header=TRUE)

library(ggplot2)    
px <- ggplot(data = dat , aes(x = Types , y = Value , Colour = Types ))
px + geom_bar(stat = "identity" ,color = "#FFFFFF" , fill = "dodgerblue3") +
  geom_text(aes(label=Value), position=position_dodge(width=0.9), hjust= -.25,vjust=0.25 ,size =3.5 , angle = 90)

enter image description here

最佳答案

geom_text的通过位置在 y 轴上使用 y = Value + 2 * sign(Value)

library(ggplot2)
ggplot(dat, aes(Types, Value)) + 
    geom_bar(stat = "identity" ,color = "#FFFFFF" , fill = "dodgerblue3") +
    geom_text(aes(y = Value + 2 * sign(Value), label = Value), 
              position = position_dodge(width = 0.9), 
              size = 3.5 , angle = 90)

enter image description here

我在我的情节上做的另一个带有轻微视觉调整的情节:
由于您有带条的数字,因此您不需要 y 轴(这是多余的)。
ggplot(dat, aes(Types, Value)) + 
    geom_bar(stat = "identity", color = "black" , fill = "grey", 
             size = 0.7, width = 0.9) +
    geom_text(aes(y = Value + 2 * sign(Value), label = Value), 
              position = position_dodge(width = 0.9), 
              size = 5) +
    theme_classic() +
    theme(axis.text.x = element_text(size = 12),
          axis.title = element_text(size = 20),
          axis.text.y = element_blank(),
          axis.line = element_blank(),
          axis.ticks = element_blank())

enter image description here

关于r - 将标签放在负和正 geom_bar 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46300666/

相关文章:

r - 如何使用 facet_grid 或 facet_wrap 保持条的厚度均匀并切换 strip 位置?

R ggplot2 按组指定单独的颜色渐变

r - 在 ggplot 上显示计数

r - 水平分解无法转换为 ggplot barplot 变量顺序

r - 具有基本计算功能的群组功能

r - 将 R 列表保存到单独的 Excel 工作表中的函数

r - 将 xtable 中底行的内容加粗

r - ggplot2中的饼图具有可变的饼图大小

r - 扩大 x Axis 上刻度线之间的间距

R 分组条形的 geom_bar 和 geom_line 标签