将标签添加到ggplot条形图 [英] Adding labels to ggplot bar chart

查看:170
本文介绍了将标签添加到ggplot条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用酒吧里的百分比来做一个黑色的酒吧情节。这可能来自qplot吗?

包:ggplot2,重塑



  x < -  data.frame(filename = c(file1,file2,file3,file4),
low = c( - 。05,.06 ,. 07, - 。14),
hi = c(.87,.98,.56,.79))
x $ tot < - x $ hi + x $ low

x < - melt(x,id ='filename')

bar < - qplot(x =因子(文件名),
y =值* 100,
填充=因子(变量),
data = x,
geom ='bar',
position ='dodge')+ coord_flip()
bar < - bar + scale_fill_manual name'',
labels = c('low',
'Hi',
Tot),
值= c('#40E0D0',
'#FF6347',
#C7C7C7))
bar < - bar + geom_text(aes(label = value * 100))+ geom_bar(color ='black')
bar < - bar + opts(panel.background = theme_rect(color = NA))
bar < - bar + opts(legend.justification ='bottom' )
print(bar)


解决方案

go:

  library(scales)
ggplot(x,aes(x = filename,fill = variable))+
geom_bar(stat =identity,ymin = 0,aes(y = value,ymax = value),position =dodge)+
geom_text(aes(x = filename,y = value, ymax = value,label = value,
hjust = ifelse(sign(value)> 0,1,0)),
position = position_dodge(width = 1))+
scale_y_continuous labels = percent_format())+
coord_flip()


I would like to do a bar plot outlined in black with percentages inside the bars. Is this possible from qplot? I get the percentages to appear but they don't align with the particular bars.

packages: ggplot2, reshape

x <- data.frame(filename = c("file1", "file2", "file3", "file4"),
                    low = c(-.05,.06,.07,-.14),
                    hi = c(.87,.98,.56,.79))
x$tot <- x$hi + x$low

x <- melt(x, id = 'filename')

bar <- qplot(x = factor(filename), 
             y = value*100,
             fill = factor(variable),
             data = x,
             geom = 'bar',
             position = 'dodge') + coord_flip()
bar <- bar + scale_fill_manual(name = '',
                               labels = c('low',
                                          'Hi',
                                          "Tot"),
                               values = c('#40E0D0',
                                          '#FF6347',
                                          "#C7C7C7")) 
bar <- bar + geom_text(aes(label = value*100))+geom_bar(colour = 'black')
bar <- bar + opts(panel.background = theme_rect(colour = NA))
bar <- bar + opts(legend.justification = 'bottom')
print(bar)

解决方案

Here you go:

library(scales)
ggplot(x, aes(x = filename, fill = variable)) +
  geom_bar(stat="identity", ymin=0, aes(y=value, ymax=value), position="dodge") +
  geom_text(aes(x=filename, y=value, ymax=value, label=value, 
                hjust=ifelse(sign(value)>0, 1, 0)), 
            position = position_dodge(width=1)) +
  scale_y_continuous(labels = percent_format()) +
  coord_flip()

这篇关于将标签添加到ggplot条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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