简体   繁体   English

如何在 ggplot2 中的水平条形图之外进行注释

[英]How do I annotate outside of horizontal bar plot in ggplot2

I have been searching for a way to add text next to horizontal stacked bar plots but outside of the plotting area, but I can't seem to find a solution.我一直在寻找一种在水平堆积条形图旁边但在绘图区域之外添加文本的方法,但我似乎找不到解决方案。

here is some example data and the plot:这是一些示例数据和情节:

df <- data.frame(x = c('A', 'A', 'B', 'B', 'C', 'C'),
                 y = c(3, 7, 5, 5, 6, 4),
                 z = c(1, 0, 1, 0, 1, 0),
                 a = c(40, 40, 50, 50, 60, 60))

ggplot() +
  geom_bar(data = df, aes(x = x, y = y, fill = z), stat = 'identity') +  
  coord_flip() +
  theme(
    panel.background = element_blank(),
    axis.line.y = element_blank(),
    axis.ticks.y = element_blank(),
    axis.line = element_line(colour = 'black'),
    legend.position = 'none')

在此处输入图片说明

What I would like to do is add the values of 'a' to the right of the horizontal bars.我想要做的是将 'a' 的值添加到水平条的右侧。 I have tried to do this with annotate but it results in the axis extending and also, for longer labels, part ends up being cut off.我试图用 annotate 来做到这一点,但它会导致轴延伸,而且对于更长的标签,部分最终会被切断。

在此处输入图片说明

I have also seen that coord_cartesian can be used to specify the range of interest on the axis and stop the label being clipped, but ggplot wont let me use it along with coord_flip.我还看到 coord_cartesian 可用于指定轴上的感兴趣范围并停止剪切标签,但 ggplot 不允许我将它与 coord_flip 一起使用。

How can I acheive the desired labels?如何获得所需的标签?

This gives me quite fair result:这给了我相当公平的结果:

  library(ggplot2)
  df <- data.frame(x = c('A', 'A', 'B', 'B', 'C', 'C'),
                   y = c(3, 7, 5, 5, 6, 4),
                   z = c(1, 0, 1, 0, 1, 0),
                   a = c(40, 40, 50, 50, 60, 60))

  ggplot(data = df, aes(x = x, y = y, fill = as.factor(z))) +
    geom_bar( stat = 'identity') +  
    coord_flip() +
    geom_text(aes( label = sprintf("%.1f",a), y= 10.5),  vjust = 1)+
    #guides(fill=FALSE)+
    theme(
      panel.background = element_blank(),
      axis.line.y = element_blank(),
      axis.ticks.y = element_blank(),
      axis.line = element_line(colour = 'black'),
      legend.position = 'none')+
    scale_y_continuous(breaks = seq(0,10,2))

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM