根据ggplot中的条件将点添加到堆叠条形图中

时间:2020-10-02 02:37:45

标签: r ggplot2

我有一个堆积的条形图,它显示了多个公司中不同建筑物的大小分布的频率。

我正在为数据集中的每个公司复制此图表,并且对于每个公司,我想在堆栈中添加一个点来表示其公司建筑物的大小。我能够设置条形图并向图中添加点。但是,我无法弄清楚如何将点放置在正确的位置。

这是我的代码:

function f1(team: Team) {

    const startDate: Timestamp = team.startDate;

    const uid: UidProperties | undefined = team['randomKey']

    const name = uid?.name;

    if ( uid !== undefined ) {
        const mail = uid.mail;
    }
}

这是我到目前为止所拥有的。

Current

我想弄清楚如何为公司“ a”执行此操作,因此图表如下所示:

Desired

我正在考虑开始,我需要创建一个向量来显示该公司的Data<-data.frame(Location = c("HQ", "Plant", "Warehouse", "Office", "HQ","Plant", "Warehouse","Office","HQ","Plant","Warehouse","Office"), Company=c("a","a","a","a","b","b","b","b","c","c","c","c"), Staff=c("Small","Medium","Large","Medium","Small","Medium","Medium","Large","Large","Large","Small","Small")) ggplot(Data,aes(x=Location,fill=Staff))+ geom_bar(position = 'fill')+ geom_point(aes(y = stat(..count../sum(..count..)), color = Staff), stat = 'count', position = position_fill(0.5), size = 5)+ scale_color_manual(values = 'black', limits = "Medium") 箱:staff

1 个答案:

答案 0 :(得分:1)

以下内容应符合您的要求。 (为了方便在公司之间进行切换,我还将其包装在一个函数中。)

library(dplyr)

show.company.point <- function(company.name) {
  p <- ggplot(Data,
              aes(x = Location, fill = Staff))+
    geom_bar(position = 'fill')+
    geom_point(data = . %>%
                 mutate(alpha = Company == company.name) %>% 
                 group_by(Location, Staff) %>%
                 summarise(n = n(),
                           alpha = any(alpha)) %>%
                 ungroup(),
               aes(y = n, alpha = alpha, group = Staff),
               position = position_fill(0.5, reverse = F),
               size = 5, show.legend = F) +
    ggtitle(paste("Company", company.name)) +
    scale_alpha_identity()
  return(p)
}

show.company.point("a")
show.company.point("b")
show.company.point("c")

results