使用ggplot2使用偏移基线创建条形图

问题描述

如果我使用认的R graphics程序包,则可以绘制基线交错的图。

这是一个使用CPTtools软件包的示例(可在github上找到)

library(devtools)
install_github("ralmond/CPTtools")
library(CPTtools)

margins <- data.frame (
     Trouble=c(Novice=.19,Semester1=.24,Semester2=.28,Semseter3=.20,Semester4=.09),NDK=c(Novice=.01,Semester1=.09,Semester2=.35,Semseter3=.41,Semester4=.14),Model=c(Novice=.19,Semester1=.28,Semester2=.31,Semseter3=.18,Semester4=.04)
    )
margins <- as.matrix(margins)
baseline <- apply(margins[1:2,],2,sum)
     
stackedBarplot(margins,offset=-baseline,main="Marginal distributions for NetPASS skills",sub="Baseline at 2nd Semester level.",col=hsv(223/360,.2,0.10*(5:1)+.5))

这将产生输出

stacked barplot

键是offset参数,该参数传递给barplot函数

由于各种原因,我试图使用ggplot重写CPTtools的图形。我不知道如何调整堆叠条形图的位置。我最近来的是

library(tidyverse)
margins <- data.frame (
      Trouble=c(Novice=.19,Semester4=.04)
)
tibble::rownames_to_column(margins,var="Level") %>%
  tidyr::pivot_longer(-Level,names_to="Attribute",values_to="probability") ->
  marg
marg %>% filter(Level=="Novice" | Level=="Semester1") %>%
  group_by(Attribute) %>% summarize(baseline=sum(probability)) ->
  bases

ggplot(marg,aes(Attribute,probability,fill=Level)) +
  geom_col(position=position_stack() +
  scale_fill_brewer(palette="Blues")

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)