在分组的条形图R上将X轴标签旋转45度 [英] rotate X axis labels 45 degrees on grouped bar plot R
问题描述
如何在R中的分组条形图上将X轴标签旋转45度?
How can I rotate the X axis labels 45 degrees on a grouped bar plot in R?
我已尝试在此处建议的解决方案,但得到了一件非常混乱的事情,标签似乎已被添加多次(仅显示轴部分以保护数据隐私):
I have tried the solution suggested here but got something very messy, the labels seem to have been added multiple times (only showing the axis part to protect data privacy):
此解决方案(gridBase)也是对于我来说不成功,由于某种原因,我收到以下错误:
This solution (gridBase) was also unsuccessful for me, for some reason I get the following error:
无法弹出顶级视口(网格和图形输出混合吗?)"
"Cannot pop the top-level viewport (grid and graphics output mixed?)"
PS. Most people seem to recommend this solution in R base but I am stuck with that too because I don't understand what data they are referring to (I need some kind of example data set to understand new command lines...).
这些解决方案是否无效,因为我的Barplot是一个分组的Barplot?还是应该起作用?任何建议都欢迎,我已经停留了很长时间.谢谢.
Are these solutions not working because my barplot is a grouped barplot? Or should it work nevertheless? Any suggestions are welcome, I have been stuck for quite some time. Thank you.
[edit]根据要求,我要添加用于生成上面图片的代码(基于text()解决方案之一):
[edit] On request I am adding the code that I used to generate the picture above (based on one of the text() solutions):
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)
推荐答案
我不是精通基本图的人,所以也许我的解决方案不是很简单.我认为在这里使用ggplot2更好.
I am not a base plot proficient, so maybe my solution is not very simple. I think that using ggplot2 is better 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
这篇关于在分组的条形图R上将X轴标签旋转45度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!