繁体   English   中英

如何分组ggplot geom_bar R

[英]How to group in ggplot geom_bar R

我很努力地尝试使我无法对ggplot geom_bar进行分组。

我有一个模拟数据帧结构,尽管实际数据帧明显更大:

df<-data.frame(id=1:12,
    count=c(12,5,33,6,43,12,8,56,14,43,36,32),
    name=c("A","A","A","B","B","B","B","B","B","C","C","D"),
    stringsAsFactors=F)

使用模拟或在这种情况下使用真实数据帧,我得到一个图

ggplot(df, aes(x=id,y=count)) + geom_bar(stat="identity")

在此处输入图片说明

这将按照正确的顺序(在数据框中显示)绘制所有内容,但是,沿着x轴而不是数字id值,我想将名称作为一个组使用:前三个名称为“ A”值,“ B”代表六个值,“ C”代表下两个值,“ D”代表最终值-在完整数据集的情况下为专有名称。

我感觉这应该很容易,只要我的数据帧格式正确即可。 任何帮助,不胜感激。

我们可以在scale_x_discrete函数中指定标签。

library(ggplot2)

df<-data.frame(id=1:12,
               count=c(12,5,33,6,43,12,8,56,14,43,36,32),
               name=c("A","A","A","B","B","B","B","B","B","C","C","D"),
               stringsAsFactors=F)

ggplot(df, aes(x = factor(id), y = count)) + 
  geom_bar(stat="identity") +
  scale_x_discrete(name = "name", labels = df$name)

在此处输入图片说明

如果每个组只需要一个标签,则可以执行以下操作以将标签保留在每个组的第一栏中。

library(dplyr)

df2 <- df %>%
  group_by(name) %>%
  mutate(name2 = ifelse(row_number() > 1, "", name)) %>%
  ungroup()

ggplot(df, aes(x = factor(id), y = count)) + 
  geom_bar(stat = "identity") +
  scale_x_discrete(name = "name", labels = df2$name2) +
  theme(axis.ticks.x = element_blank())

在此处输入图片说明

或使用facet_grid

ggplot(df, aes(x = factor(id), y = count)) + 
  geom_bar(stat = "identity") +
  scale_x_discrete(name = "id") +
  facet_grid(. ~ name, space = 'free_x', scales = 'free_x')

在此处输入图片说明

这是一种实现方法,我们分别计算字母的位置和分隔符以保持清晰度,并使用scale_x_continuous / breaks / labels来绘制它们

l <- rle(df$name)$lengths
letter_pos <- cumsum(c(0,head(l,-1))) + l/2 + .5
sep_pos <- cumsum(l) + .5

ggplot(df, aes(x=id,y=count)) + geom_bar(stat="identity") +
  scale_x_continuous(breaks = c(letter_pos, sep_pos),
                     labels = c(unique(df$name),rep("|",length(letter_pos))))

暂无
暂无

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

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