在ggplot中分组的条形图中的标记条

时间:2017-09-15 03:39:13

标签: r ggplot2

此图的主要目标是在三个组中对AB进行比较,但我希望onetwo和{{ 1}}除此之外,还有。使用下面的代码,我可以制作一个几乎我想要的分组条形图。但是我需要在它下方的每个栏的名称,因为传说是如此丑陋。

我该怎么做?

three

enter image description here

4 个答案:

答案 0 :(得分:3)

添加geom_text并确保它以与条形图相同的方式避开:

# width = 0.9 should be the default for dodged bars but set
#  it explicitly to be sure
dodger = position_dodge(width = 0.9)
ggplot(df, aes(x = m.group, y = m.value)) + 
    geom_bar(aes(fill = m.names), position = dodger, stat = "identity") +
    scale_fill_manual(values=c("gray75", "gray75","gray75", "gray40","gray40","gray40", "blue", "red", "green" ),
                      guide = "none") +
    geom_text(aes(x = m.group, group = m.names, label = m.names, y = 0), 
              position = dodger,
              vjust = 1, colour = "black")

enter image description here

答案 1 :(得分:3)

按组分组可能也适用于此案例:

fill.values = c("gray75", "gray75","gray75", 
                "gray40","gray40","gray40", 
                "blue", "red", "green")
names(fill.values) = levels(df$m.names)

> fill.values
      A1       A2       A3       B1       B2       B3      one    three      two 
"gray75" "gray75" "gray75" "gray40" "gray40" "gray40"   "blue"    "red"  "green" 

ggplot(df,
       aes(x = m.names, y = m.value, fill = m.names)) +
  geom_col() +
  scale_fill_manual(values = fill.values, guide = F) +
  facet_wrap(~m.group, scales = "free_x") +
  theme_bw()

enter image description here

答案 2 :(得分:1)

我们可以使用geom_label

dodger = position_dodge(width = 0.9)
ggplot(df, aes(x = m.group, y = m.value)) + 
    geom_bar(aes(fill = m.names), position = dodger, stat = "identity") +
    scale_fill_manual(values=c("gray75", "gray75","gray75", 
                  "gray40","gray40","gray40", "blue", "red", "green" ),
                      guide = "none") +
     theme(axis.text.x=element_blank(),  
      axis.ticks.x=element_blank()) +
    geom_label(aes(x = m.group, group = m.names, label = m.names, y = 0), 
              position = dodger,
              vjust = 1, colour = "black")

enter image description here

答案 3 :(得分:1)

好像你可能想要这样:

require(ggplot2)

ggplot(df, aes(x = m.names, y = m.value)) + 
  geom_bar(aes(fill = m.names), stat = "identity") +
  scale_fill_manual(values=c("gray75", "gray75","gray75", "gray40",
                             "gray40","gray40", "blue", "red", "green" )) +
  facet_grid(~m.group, scales = "free_x", space = "free_x") +
  theme(strip.text.x = element_blank(),
        panel.spacing = unit(0, "lines"))

输出:

enter image description here

诀窍是在这里用m.names而不是m.groups绘制x。然后我们可以通过m.group对这些条形进行分区,以便按照你想要的方式呈现它们。