在第一个栏或以上而不是图例中写入组标签

时间:2014-11-15 20:41:18

标签: r ggplot2

我有一个堆积的条形图,其中包含以下数据

df <- expand.grid(name = c("oak","birch","cedar"),
    sample = c("one","two"),
    type = c("sapling","adult","dead"))
df$count <- sample(5:200, size = nrow(df), replace = T)

我生成一个条形图,并尝试将组标签添加到它:

ggplot(df, aes(x = name, y = count, fill = type)) +
   geom_bar(stat = "identity") +
   coord_flip() +
   theme(legend.position="none") +
   geom_text(aes(label = type, position = "stack")) 

它产生: Barplot with ugly labels

出现两到三个问题:

  1. 如何让标签仅显示在顶栏?

  2. 如何使标签出现在条形区域的中央?

  3. 可选:如何使标签显示在通过箭头连接到其部分的顶部栏的顶部?

1 个答案:

答案 0 :(得分:2)

上面提到了一个链接。那会对你有所帮助。在这里,我有另一个建议。

set.seed(123)
df <- expand.grid(name = c("oak","birch","cedar"),
                  sample = c("one","two"),
                  type = c("sapling","adult","dead"))
df$count <- sample(5:200, size = nrow(df), replace = T)

### Arrange a data frame (summing up sample one and two)
library(dplyr)
ana <- df %>%
        group_by(name, type) %>%
        summarise(total = sum(count))

# Draw a figure once        
bob <- ggplot(ana, aes(x = name, y = total, fill = type)) +
       geom_bar(stat = "identity", position = "stack")

# Get a data frame for ggplot      
cathy <- ggplot_build(bob)$data[[1]]

# calculate text position & add text labels
cathy$y_pos <- (cathy$ymin + cathy$ymax) / 2
cathy$label <- rep(c("sampling", "adult", "dead"), times = 3)

# Subset the data for labeling for the top bar
dan <- cathy[c(7:9), ]

# Draw a figure again
bob + 
annotate(x = dan$x, y = dan$y_pos, label = dan$label, geom="text", size=3) +
coord_flip()

enter image description here