2013-11-27 207 views
6

如何在R中的分組條形圖上旋轉X軸標籤45度?在分組條形圖上旋轉X軸標籤45度R

我試圖解決建議here但得到的東西很凌亂,標籤似乎已經多次添加(只顯示軸的一部分,以保護數據隱私): enter image description here

This solution(gridBase)也對我來說不成功,出於某種原因,我得到以下錯誤:

"Cannot pop the top-level viewport (grid and graphics output mixed?)"

PS。 大多數人似乎建議在R基地this solution,但我也堅持這一點,因爲我不明白他們指的是什麼數據(我需要某種示例數據集來了解新的命令行...)。

這些解決方案是不是工作,因爲我的barplot是一個分組的barplot?或者它應該工作嗎?任何建議都是值得歡迎的,我一直堅持了一段時間。謝謝。

[編輯]在請求我加入代碼,我用於生成上述畫面(基於文本的一個()溶液):

data <- #this is a matrix with 4 columns and 20 rows; 
     #colnames and rownames are specified. 
     #the barplot data is grouped by rows 

lablist <- as.vector(colnames(data)) 

barplot(data, beside=TRUE, col=c("darkred","red","grey20","grey40")) 
text(1:100, par("usr")[1], labels=lablist, srt=45, pos=1, xpd=TRUE) 
+2

什麼是你的代碼正在使用?如果你能制定一個可重複的例子,這將是很好的(見http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。 –

+0

不知道它是否有幫助,但我添加了讓我獲得上述屏幕截圖的代碼。我不能透露數據,但我期望任何隨機數據都可以。 – biohazard

+0

您需要稍微改變標籤的垂直位置(「text」中的第二個參數),並且您在'labels'參數中遇到了矢量回收,這就是爲什麼文本如此混亂。你預期的結果是什麼? – Thomas

回答

5

嘗試第一個答案:

x <- barplot(table(mtcars$cyl), xaxt="n") 
labs <- paste(names(table(mtcars$cyl)), "cylinders") 
text(cex=1, x=x-.25, y=-1.25, labs, xpd=TRUE, srt=45) 

但變化CEX = 1到CEX = 0.8或在文本()函數0.6:

text(cex=.6, x=x-.25, y=-1.25, labs, xpd=TRUE, srt=45) 

在您發佈的照片​​,它似乎米e標籤太大了。 cex設置這些標籤的大小。

6

我不是一個精通基本情節,所以也許我的解決方案不是很簡單。我認爲在這裏使用ggplot2更好。

enter image description here

def.par <- par(no.readonly = TRUE) 

## divide device into two rows and 1 column 
## allocate figure 1 for barplot 
## allocate figure 2 for barplot labels 
## respect relations between widths and heights 

nf <- layout(matrix(c(1,1,2,2),2,2,byrow = TRUE), c(1,3), c(3,1), TRUE) 
layout.show(nf) 

## barplot 
par(mar = c(0,1,1,1)) 
set.seed(1) 
nKol <- 8 ## you can change here but more than 11 cols 
      ## the solution is not really readable 
data <- matrix(sample(1:4,nKol*4,rep=TRUE),ncol=nKol) 
xx <- barplot(data, beside=TRUE, 
       col=c("darkred","red","grey20","grey40")) 

## labels , create d ummy plot for sacles 
par(mar = c(1,1,0,1)) 
plot(seq_len(length(xx)),rep(1,length(xx)),type='n',axes=FALSE) 
## Create some text labels 
labels <- paste("Label", seq_len(ncol(xx)), sep = " ") 
## Plot text labels with some rotation at the top of the current figure 
text(seq_len(length(xx)),rep(1.4,length(xx)), srt = 90, adj = 1, 
    labels = labels, xpd = TRUE,cex=0.8,srt=60, 
    col=c("darkred","red","grey20","grey40")) 

par(def.par) #- reset to default 
3

我曾與一個分組柱狀圖同樣的問題。我假設你只需要在每個組下面放一個標籤。我可能是錯誤的,因爲你沒有明確說明,但這似乎是這種情況,因爲你的標籤在圖像中重複。在這種情況下,你可以使用斯圖提出的解決方案,雖然你有當你把它提供給文本函數colMeans適用於x變量:

x <- barplot(table(mtcars$cyl), xaxt="n") 
labs <- paste(names(table(mtcars$cyl)), "cylinders") 
text(cex=1, x=colMeans(x)-.25, y=-1.25, labs, xpd=TRUE, srt=45)