【问题标题】:How to wrap long titles in lattice graphics in R?如何在 R 的格子图形中包装长标题?
【发布时间】:2014-12-25 21:40:09
【问题描述】:

我需要为使用 HH 包中的 likert 函数创建的图形添加一个长标题,该函数使用格子,但它(格子)没有此功能。有没有办法做到这一点?

我的代码

library(HH)
ppi <- 150
jpeg("ssb_%02d.jpg", width=7*ppi, height=4*ppi, res=ppi)

for(i in 1:2){
    plot_obj <- likert(Grup ~ . | Grup, data = ssb, as.percent = TRUE, positive.order = TRUE,
        main=list(label = items[i,], cex=1.2), 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()

我的数据

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")

标题项目

items <- structure(list(V1 = structure(1:2, .Label = c("1. În cele mai multe privinţe, viaţa mea corespunde idealului meu.", 
"2. Până în prezent am primit cele mai importante lucruri pe care le doresc în viață."
), class = "factor")), .Names = "V1", class = "data.frame", row.names = c(NA, 
-2L))

更新

图形标题不是直接添加的,而是从数据框中动态添加的,并且数据框是从 .csv 文件加载的。如果按照 cmets 中的建议,我将 \n 添加到 .csv 文件中的长标题,这将不起作用。

【问题讨论】:

  • 我认为应该是\n。例如,"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\ntempor incididunt ut labore et dolore magna aliqua."
  • 我的答案中的代码 sn-p 对我有用(在\n 处断行。
  • 我会使用strwrap() 来自动进行文本换行。如果您的长标题存储在名为mainText 的字符串中,只需执行mainFormatted &lt;- paste(strwrap(mainText, width=45), collapse="\n") 之类的操作即可获得大约45 个字符宽的包装版本。

标签: r graphics lattice word-wrap


【解决方案1】:

感谢@josh-obrien,我解决了我的问题。现在,当图形标题超过 70 个字符时,它会被换成 65 个字符宽的版本。

library(HH)
ppi <- 150
jpeg("ssb_%02d.jpg", width=7*ppi, height=4*ppi, res=ppi)

for(i in 1:2){

    if(stri_length(items[i,])>70){
        graphic.title <- paste(strwrap(items[i,], width = 65), collapse="\n")
    } else {
        graphic.title <- items[i,]
    }

    plot_obj <- likert(Grup ~ . | Grup, data = ssb, as.percent = TRUE, positive.order = TRUE,
    main=list(label = graphic.title, cex=1.2), 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    相关资源
    最近更新 更多