2013-11-27 202 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)