[英]How to add labels as percentages to the lattice stacked bar charts in R?
I have created some stacked bar charts with the likert
function from the HH
package, that uses lattice
. 我已经从
HH
软件包中使用likert
函数创建了一些堆叠的条形图,它们使用了lattice
。 Now I want to add labels represented as percentages inside to each segment of the charts, or, better, only to that segments that have a sufficient width for that. 现在,我想在图表的每个部分中添加以百分比表示的标签 ,或者更好的是,仅向具有足够宽度的那些部分添加标签 。 How to do this?
这个怎么做? I mention that my data are represented as frequencies, not as percentages.
我提到我的数据以频率表示,而不是以百分比表示。
My data : 我的资料 :
ssb <- structure(list(`Strongly Disagree` = c(2L, 1L), `Moderate Disagree` = 1:2,
`Slightly Disagree` = c(3L, 1L), `Slightly Agree` = c(1L,
5L), `Moderate Agree` = 4:5, `Strongly Agree` = c(9L, 6L),
Grup = c("Experimental grup", "Control grup")), .Names = c("Strongly Disagree",
"Moderate Disagree", "Slightly Disagree", "Slightly Agree", "Moderate Agree",
"Strongly Agree", "Grup"), row.names = c("1", "2"), class = "data.frame")
My code : 我的代码 :
library(HH)
ppi <- 150
jpeg("ssb_%02d.jpg", width=7*ppi, height=4*ppi, res=ppi)
plot_obj <- likert(Grup ~ . | Grup, data = ssb, as.percent = TRUE, positive.order = TRUE,
main="", xlab=list(label="Percent", cex=1.1),
ylab="", ylab.right = list("Subjects per group", cex=1.1),
scales = list(y = list(relation = "free", labels=""), cex=1.1),
layout = c(1, 2), auto.key=list(space="bottom", columns=3, title="", cex=1.1))
print(plot_obj)
dev.off()
Thanks to Deepayan Sarkar, this question was solved: 感谢Deepayan Sarkar,这个问题得以解决:
library(HH)
library(latticeExtra)
ppi <- 150
jpeg("ssb_%02d.jpg", width=7*ppi, height=4*ppi, res=ppi)
plot_obj <- likert(Grup ~ . | Grup, data = ssb, as.percent = TRUE, positive.order = TRUE,
main="", xlab=list(label="Percent", cex=1.1),
ylab="", ylab.right = list("Subjects per group", cex=1.1),
scales = list(y = list(relation = "free", labels=""), cex=1.1),
layout = c(1, 2), auto.key=list(space="bottom", columns=3, title="", cex=1.1))
plot_obj <- plot_obj +
layer({
id = which(x > 0)
xx = 0.5 * (cumsum(x[id]) + cumsum(c(0, x[id][-length(id)])))
panel.text(xx, y[id], labels = paste(x[id], "%", sep = ""))
id = which(x < 0)
xx = 0.5 * (cumsum(x[id]) + cumsum(c(0, x[id][-length(id)])))
panel.text(xx, y[id], labels = paste(-x[id], "%", sep = ""))
})
print(plot_obj)
dev.off()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.