2015-04-28 77 views
4

我想繪製類似於(from this paper)的圖形,其中圖標(在本例中爲小圖)用作刻度標籤。圖標作爲R中的x軸標籤

enter image description here

我走這麼遠,其中的圖標都或多或少妥善安置: enter image description here 這是代碼:

library(igraph)  
npoints <- 15 
y <- rexp(npoints) 
x <- seq(npoints) 

par(fig=c(0.05,1,0.3,1), new=FALSE) 
plot(y, xlab=NA, xaxt='n', pch=15, cex=2, col="red") 
lines(y, col='red', lwd=2) 

xspan <- 0.9 
xoffset <- (0.07+0.5/npoints)*xspan 
for(i in 1:npoints){ 
    x1 <- (xoffset+(i-1)/npoints)*xspan 
    x2 <- min(xspan*(xoffset+(i)/npoints),1) 
    par(fig=c(x1,x2,0,0.5), new=TRUE) 
    plot(graph.ring(i), vertex.label=NA) 
} 

然而,如果點的數量的增加(如npoints <- 15)它抱怨,因爲沒有地方的圖標:

Error in plot.new() : figure margins too large 

我不知道有沒有更自然的方法來做到這一點,以便它適用於任何(合理的)點數。

歡迎任何建議。

回答

5
library(igraph)  
npoints <- 15 
y <- rexp(npoints) 
x <- seq(npoints) 

# reserve some extra space on bottom margin (outer margin) 
par(oma=c(3,0,0,0)) 
plot(y, xlab=NA, xaxt='n', pch=15, cex=2, col="red") 
lines(y, col='red', lwd=2) 

# graph numbers 
x = 1:npoints 

# add offset to first graph for centering 
x[1] = x[1] + 0.4 
x1 = grconvertX(x=x-0.4, from = 'user', to = 'ndc') 
x2 = grconvertX(x=x+0.4, from = 'user', to = 'ndc') 

# abline(v=1:npoints, xpd=NA) 
for(i in x){ 

    print(paste(i, x1[i], x2[i], sep='; ')) 

    # remove plot margins (mar) around igraphs, so they appear bigger and 
    # `figure margins too large' error is avoided 
    par(fig=c(x1[i],x2[i],0,0.2), new=TRUE, mar=c(0,0,0,0)) 
    plot(graph.ring(i), vertex.label=NA) 

    # uncomment to draw box around plot to verify proper alignment: 
    # box() 

} 

enter image description here

+0

謝謝!請注意,最左邊的圖形並沒有很好地對齊(例如,當你有10個點時,它會更清楚)。 – alberto

+1

是的,我也注意到了。如果您在繪製圖形後添加了一個帶有「box()」的多餘行,您將會看到該圖表框很好地對齊,但圖形本身並未在該框內居中。所以對於最左邊的圖表,您可能需要手動添加偏移量。將添加到帖子。 – koekenbakker

+0

太棒了!爲了以防萬一,還有一件事情是微不足道的。爲什麼使用ggplot而不是plot會把它全部打破? – alberto