2015-10-14 59 views
2

我試圖用10^n的值在每個第三個刻度處標記一個軸,格式化爲上標。我正在使用grid圖形。我在做一些粗心大意的事情。這裏有一個MWE(或我看到有一些運動,稱之爲reprex):替代矢量的Plotmath表達式

library("grid") 
grid.newpage() 
axisVP <- viewport(width = unit(6, "inches"), height = unit(0.01, "inches")) 
pushViewport(axisVP) 
labs <- c(1, "", "", expression(10^{-3}), "", "", expression(10^{-6}), "", "", 
    expression(10^{-9}), "", "", expression(10^{-12})) 
grid.xaxis(at = seq(0, 1, length.out = 15)[-c(1,15)], label = labs) 

不過,這僅與標籤1.第一跳在str(labs)看它是與長度13的表達如預期。表達式被grid.xaxis接受。所以我不太確定爲什麼只顯示第一個值。我已經在SO上探討了相關的問題,但大多數似乎都將單個表達式作爲軸標籤或標題處理,而不是一系列表達式。大多數涉及軸標籤的問題都試圖使用專門的功能標記每個刻度。

回答

2

這裏就是我想要做的:

library(grid) 
grid.newpage() 
axisVP <- viewport(width = unit(6, "inches"), height = unit(0.01, "inches")) 
pushViewport(axisVP) 

## First plot an axis with all ticks and no labels 
ticks_at <- seq(1/15, 14/15, length.out=13) 
grid.xaxis(at = ticks_at, label=FALSE) 

## Then add labels where you want them 
labs <- parse(text=c("1", "10^{-3}", "10^{-6}", "10^{-9}", "10^{-12}")) 
## Alternatively, use this, though in practice it's more cumbersome 
# labs <- c(expression(1), expression(10^{-3}), expression(10^{-6}), 
#   expression(10^{-9}), expression(10^{-12})) 
labs_at <- seq(1/15, 14/15, length.out=5) 
grid.xaxis(at = labs_at, label = labs) 

enter image description here

+0

謝謝!這裏有一些魔法,我必須學習'parse'和'text'。我也非常感謝你們提供的替代(並且在概念上更爲優越)的方式來傳達序列。而通常更精簡的代碼。 –

+1

不客氣!要了解'parse()'在這種情況下做了什麼,請參閱[here](https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Internal-representation)和R語言定義中的[here](https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Expression-objects)。 (事實證明,這是極少數情況下,你應該使用'parse()'來構造R語言對象。爲了更好的選擇,請參閱[計算語言]部分(https:/ /cran.r-project.org/doc/manuals/r-release/R-lang.html#Computing-on-the-language)。) –

+0

(可能值得注意的是,如果你想讓你的一些表達式不要打印任何東西,你需要將它們設置爲'phantom(。)'。) –