我正在尝试使用'HH'包中的plot.likert()在李克特类型数据集中为每个答案选项的子表在子图中显示百分比。该图的目的是比较调查人口子组中的百分比。 我期望的结果是这样:
我正在使用下面的代码获得带有子表的图
示例数据框:
df <- data.frame ("Strongly_Disagree" = c(1,28,5,33,18,14,8,9), "Disagree" = c(6,15,8,10,11,4,5,6),
"No_opinion" =c(4,3,8,10,9,20,45,2),
"Agree"=c(50,4,2,8,10,9,7,7),
"Strongly_Agree"=c(59,4,9,10,8,4,14,30),"Question" = c("CityA","CityB","CityC","Female","Male","Important","Not important","Neutral"),
"Subtable" = c("City","City","City","Gender","Gender","Attitude","Attitude","Attitude"))
第一个绘图的代码:
library("HH")
Plot1 <- likert(Question ~ . | Subtable, df,
as.percent=TRUE,
ylab=NULL,
main=
list("Multiple Panel Plot without Percentage Labeling", x=unit(.35, "npc")),
strip.left=strip.custom(bg="gray85"),
strip=FALSE,
par.strip.text=list(cex=.6, lines=5),
positive.order=TRUE,
layout=c(1,3), # Last number ist number of Subtables
scales=list(y=list(relation="free")))
我还设法用下面的功能标记百分比(我在这篇文章中有此功能):
displaying percentage per category in likert stacked proportion barplots
我修改了该函数,将百分比四舍五入到逗号后的小数点后两位。
myPanelFunc <- function(...){panel.likert(...)vals <- list(...) `DF <- data.frame(x=vals$x, y=vals$y, groups=vals$groups)`
grps <- as.character(DF$groups)for(i in 1:length(origNames)){
grps <- sub(paste0('^',origNames[i]),i,grps)}
DF <- DF[order(DF$y,grps),]
DF$correctX <- ave(DF$x,DF$y,FUN=function(x){
x[x < 0] <- rev(cumsum(rev(x[x < 0]))) - x[x < 0]/2
x[x > 0] <- cumsum(x[x > 0]) - x[x > 0]/2
return(x)})
subs <- sub(' Positive$','',DF$groups)
collapse <- subs[-1] == subs[-length(subs)] & DF$y[-1] == DF$y[-length(DF$y)]
DF$abs <- abs(DF$x)
DF$abs[c(collapse,FALSE)] <- DF$abs[c(collapse,FALSE)] + DF$abs[c(FALSE,collapse)]
DF$correctX[c(collapse,FALSE)] <- 0
DF <- DF[c(TRUE,!collapse),]
DF$perc <- ave(DF$abs,DF$y,FUN=function(x){x/sum(x) * 100})
panel.text(x=DF$correctX, y=DF$y, label=paste0(sprintf("%1.1f%%", DF$perc)), cex=0.7)}
但是问题是,我没有设法将这两个代码组合在一起,所以我有一个带有子表和百分比标签的图。 有没有一种方法可以修改此代码以在带有子表的图中显示百分比? 在这方面的任何帮助,我将不胜感激,因为我在HH软件包或互联网上其他任何地方的说明中都找不到论点。提前谢谢您!