添加标签ggplot条形图(Adding labels to ggplot bar chart)

2019-06-17 13:19发布

我想这样做的黑边与酒吧内的百分比柱状图。 这可能从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 = 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)

Answer 1:

干得好:

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



Answer 2:

这将是一个很好的机会,让你开始使用移开qplot ,有利于ggplot 。 这将是从长远来看要容易得多,相信我。

这里是一个开始:

library(scales)
ggplot(data = x,aes(x = factor(filename),y = value)) + 
    geom_bar(aes(fill = factor(variable)),colour = "black",position = 'dodge') + 
    coord_flip() + 
    scale_fill_manual(name = '',
                      labels = c('low',
                                 'Hi',
                                 "Tot"),
                      values = c('#40E0D0',
                                 '#FF6347',
                                 "#C7C7C7")) + 
    scale_y_continuous(labels = percent_format())

对于哲学的原因,我将离开注释一块给你...



文章来源: Adding labels to ggplot bar chart
标签: r ggplot2