将标签放在正负geom_bar上 [英] Put labels over negative and positive geom_bar

查看:169
本文介绍了将标签放在正负geom_bar上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to visualize a data using bar chart and ggplot.

我有下面的数据,当我想查看该数据时,在条形下方没有显示负值的文本.

I have the data below, when I want to vis this data the text for negative values are not showing below the 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)

推荐答案

使用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)

我在情节上所做的另一处带有轻微视觉调整的情节:
由于您的数字带有长条,因此不需要y轴(这是多余的).

Another plot with minor visual tweaks that I do on my plots:
As you have numbers with bars you don't need y-axis (it's redundant).

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())

这篇关于将标签放在正负geom_bar上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆