2016-03-03 101 views
2

我想繪製一個變量名稱及其符號。由於某些變量名稱很長,我試圖將換行符與軸標籤混合。這會導致有趣的事情在發生路線:帶表達式的軸標籤的R對齊

par(mar=c(1,12,1,1)) 

plot(y=1:6, 1:6, yaxt="n", ylim=c(1,6), ylab="") 

axis(2, at=6:1, las=1, 
    labels=c(
    expression(paste('Variable, ',rho, sep="")), 
    expression(paste('Another variable,\n',alpha, sep="")), 
    expression(paste('Also\nvariable,\n',beta, sep="")), 
    expression(paste('This\nvariable too, ',Gamma, sep="")), 
    expression(paste('Verybigname\nvariable,',C[zeta], sep="")), 
    expression(paste('Verybigname\nvariable,',C[zeta],"moretext\n",C[delta], sep="")))) 

第一行(從上往下)是我期望的人看起來像在某種程度上,這是旁軸有道理的。

其餘的行都顯示了變量名相對於表達式的第二個元素而不是軸的基本問題。在變量名和符號之間插入大空格的最後一行中,這會變得特別奇怪。

理想情況下,我希望標籤右對齊,並以刻度爲中心。

+0

我認爲你應該「手工」地對齊排列。或者用xpd = TRUE切換到'text'。 –

+0

你想要標籤在一行嗎? –

+0

@ Geo-sp no,這就是爲什麼我在變量名稱中添加了換行符 – noname

回答

1

這是我可以用text「邊手邊」定位的最好方法。 (使用'hadj'和'padj'軸的許多努力都失敗了。)爲了試圖在文本值下得到希臘語圖形,我需要使用atop函數。這又需要使用phantom。我大多用~*作爲連接器,而不是依靠paste,但在這裏使用「\ n」確實會產生一個換行符(我發現令人驚訝),所以我大多使用純粹的plotmath。順便說一句,函數paste的函數實際上並不接受sep參數。

par(mar=c(1,12,1,1)) 
plot(y=1:6, 1:6, yaxt="n", ylim=c(1,6), ylab="") 

axis(2, at=6:1, las=1, 
    labels=rep("",6)) 
text(0.5, 6:1- c(0,0,.2,.1,.1,.1), c(
    expression(Variable~~rho) , 
    expression(atop(~~Another~variable, phantom("Another~variable")~alpha) ), 
    expression(atop(paste('  Also\n variable') ,phantom("variable")~beta)), 
    expression(atop(paste('   This\nvariable too') ,phantom("   ")~Gamma)), 
    expression(atop(paste(' Verybigname\n   variable,'),phantom(" Verybigname")~C[zeta])), 
    expression( paste(' Verybigname\nvariable,',C[zeta],"moretext\n",C[delta]))), 
xpd=TRUE ,adj=1) 

enter image description here

+0

我也很驚訝,\ n工作。這就解釋了爲什麼sep =「」沒有做任何事情! – noname

0

ggplot2的溶液,使用atop對於多行。
它會自動定位標籤,只要你想

library(ggplot2) 
DF <- data.frame(x = 1:6, y = 1:6) 
labels = c(
    expression(Variable~~rho) , 
    expression(atop(~~Another~variable, phantom("Another~variable")~alpha) ), 
    expression(atop(paste('  Also\n variable') ,phantom("variable")~beta)), 
    expression(atop(paste('   This\nvariable too') ,phantom("   ")~Gamma)), 
    expression(atop(paste(' Verybigname\n   variable,'),phantom(" Verybigname")~C[zeta])), 
    expression( paste(' Verybigname\nvariable,',C[zeta],"moretext\n",C[delta]))) 

ggplot(DF, aes(x = x, y, y = y)) + 
geom_point() + 
scale_y_continuous(breaks = 1:6, labels = rev(labels)) 

ggplot and plotmath labels

我認爲這是可能使fonction來封裝混合文本plotmath標籤,但它似乎更復雜,手動創建標籤。