问题
I use the custom panel function (found here) to display data labels on the graph.
require(HH) # also loads: lattice, grid, latticeExtra
# custom panel function
myPanelFunc <- function(...){
panel.likert(...)
vals <- list(...)
DF <- data.frame(x=vals$x, y=vals$y, groups=vals$groups)
### some convoluted calculations here...
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(round(DF$perc,1),'%'), cex=0.7)
}
data(ProfChal)
origNames = colnames(ProfChal) # required for myPanelFunc
likert(x=Question ~ . , data=ProfChal[ProfChal$Subtable=="Employment sector",]
,main='Is your job professionally challenging?' # title
,as.percent=TRUE
,panel=myPanelFunc
)
However, in the resulting graph I see some labels on top of the other. Why is this happening only for some of the labels and not all of them?
回答1:
Not sure I am correct since I cannot see the data, but it looks like the first line (Academic (nonstudent)) has 0 answering strongly disagree and 4th (Private consultant/self-employed) has 0 answering Strongly disagree or disagree, which would probably be the cause of the problem. I think the solution to it could be a condition that if 0 have answered an option remove the label.
来源:https://stackoverflow.com/questions/55825651/data-labels-go-on-top-of-the-other