2012-11-04 64 views
36

我想用expression()語句在兩行中寫一個軸標籤。但是,plotmathexpression不允許這樣做(例如,下標文本出現在最右側)。我發現大約在2005年的this discussion類似的問題,但他們提供的工作並沒有轉化爲我在ggplot2中的應用。 A recent question解決了多行表達式語句的不同排列,但再次提供的解決方法不適用於此。ggplot2帶表達式的雙行標籤

例子:

p <- ggplot(mtcars,aes(x=wt,y=mpg))+ 
    geom_point()+ 
    xlab(expression(paste("A long string of text goes here just for the purpose \n of illustrating my point Weight "[reported]))) 
try(ggsave(plot=p,filename=<some file>,height=4,width=6)) 

產生下標「報道」被踢出的權利時,我想它旁邊坐到前一個單詞的圖像。 ggplot2 two line label with expression

+0

你爲什麼在這裏需要一個表達(即plotmath)?如果它只是一個強壯的話,可以在字符向量中插入一個'\ n'。 –

+0

也許我不明白你的建議,但我在標籤中加入了\ n。我需要表達以在我的應用程序中使用某些符號(例如下標和度數)。 – metasequoia

+0

對,你的例子不需要表達式(),簡單的paste()就可以。請參閱?plotmath中的atop()運算符 –

回答

46

我認爲這是一個錯誤。 (或者,您所鏈接的對話中指出「不支持多行表達式」這一事實的後果)。

是加文·辛普森提到的解決方法是:

#For convenience redefine p as the unlabeled plot 
p <- ggplot(mtcars,aes(x=wt,y=mpg))+geom_point() 

#Use atop to fake a line break 
p + xlab(expression(atop("A long string of text for the purpose", paste("of illustrating my point" [reported])))) 

enter image description here

它可以使用真正符合標打破。在下面的短的例子,其具有相同的形式作爲實施例,下標被正確地放置鄰近於文本的其餘部分,但文本的兩行不正確居中:

p + xlab(expression(paste("line1 \n line2 a" [b]))) 

enter image description here

我認爲,在這兩種情況下,當文本的上面的一行比文本的較下面的行長時,下標被放置錯誤。比較

p + xlab(expression(paste("abc \n abcd" [reported]))) 

enter image description here

p + xlab(expression(paste("abc \n ab" [reported]))) 

enter image description here

下標最終總是對準剛剛上線的右端的右側。

p + xlab(expression(paste("abcdefghijklmnop \n ab" [reported]))) 

enter image description here

+1

不錯的演示。不知道該怎麼處理下標,但是第二行的* start *稍微向右移動的原因是因爲換行符後面有一個額外的空格。輸入p + xlab(表達式(paste(「abcdefghijklmnop \ nab」[報告]))) 至少確保兩行*開始*在相同的位置......雖然承認這不會避開下標前的難看差距。 – user3482899

9

你可以使用這一招,

library(gridExtra) 
library(grid) 

element_custom <- function() { 
    structure(list(), class = c("element_custom", "element_text")) 
} 

element_grob.element_custom <- function(element, label="", ...) { 

    mytheme <- ttheme_minimal(core = list(fg_params = list(parse=TRUE, 
                 hjust=0, x=0.1))) 
    disect <- strsplit(label, "\\n")[[1]] 
    tableGrob(as.matrix(disect), theme=mytheme) 
} 

# default method is unreliable 
heightDetails.gtable <- function(x) sum(x$heights) 

ggplot(iris, aes(Sepal.Length, Sepal.Width)) + 
    geom_line() + 
    labs(x= "First~line \n italic('and a second') \n integral(f(x)*dx, a, b)")+ 
    (theme_grey() %+replace% theme(axis.title.x = element_custom())) 

enter image description here

+0

現在對我來說會非常有用... 但是不值得使用R 3.4.0和ggplot2_2.2.1 :( – julou