在ggplot2中旋转和间隔轴标签

我有一个情节,其中X轴是标签很长的因素。 虽然可能不是一个理想的可视化,现在我想旋转这些标签是垂直的。 我已经用下面的代码弄清楚了这一部分,但正如你所看到的那样,标签并不是完全可见的。

data(diamonds) diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut)) q <- qplot(cut,carat,data=diamonds,geom="boxplot") q + opts(axis.text.x=theme_text(angle=-90)) 

在这里输入图像描述

将最后一行更改为

 q + theme(axis.text.x = element_text(angle = 90, hjust = 1)) 

默认情况下,即使在旋转的情况下,轴也会在文本的中心alignment。 当你旋转+/- 90度时,你通常希望它在边缘alignment:

替代文字

上面的图片来自这篇博文 。

要使刻度标签上的文本完全可见并以与y轴标签相同的方向读取,请将最后一行更改为

 q + theme(axis.text.x=element_text(angle=90, hjust=1)) 

我想提供一个备用解决scheme,因为引入了canvas旋转function,所以在最新版本的ggtern中需要一个类似于我将要提出的强大解决scheme。

基本上,您需要使用三angular函数来确定相对位置,方法是构build一个返回element_text对象的函数,给定angular度(即度)和位置(即x,y,顶部或右侧)信息。

 #Load Required Libraries library(ggplot2) library(gridExtra) #Build Function to Return Element Text Object rotatedAxisElementText = function(angle,position='x'){ angle = angle[1]; position = position[1] positions = list(x=0,y=90,top=180,right=270) if(!position %in% names(positions)) stop(sprintf("'position' must be one of [%s]",paste(names(positions),collapse=", ")),call.=FALSE) if(!is.numeric(angle)) stop("'angle' must be numeric",call.=FALSE) rads = (angle - positions[[ position ]])*pi/180 hjust = 0.5*(1 - sin(rads)) vjust = 0.5*(1 + cos(rads)) element_text(angle=angle,vjust=vjust,hjust=hjust) } 

坦率地说,在我看来,我认为在指定angular度时,应该在ggplot2提供一个“自动”选项,以便说明上述的工作方式。

 #Demonstrate Usage for a Variety of Rotations df = data.frame(x=0.5,y=0.5) plots = lapply(seq(0,90,length.out=4),function(a){ ggplot(df,aes(x,y)) + geom_point() + theme(axis.text.x = rotatedAxisElementText(a,'x'), axis.text.y = rotatedAxisElementText(a,'y')) + labs(title = sprintf("Rotated %s",a)) }) grid.arrange(grobs=plots) 

其中产生以下内容:

例

使用+ coord_flip()

在“数据科学R”中,Wickham和Grolemund谈到了这个确切的问题。 在第3.8章“ 位置调整”中 ,他们写道:

coord_flip()切换x和y轴。 这是有用的(例如),如果你想要水平boxlot。 对于长标签也是很有用的:很难让它们在X轴上不重叠。

把这个应用到你的情节,我们只需要添加+ coord_flip()到ggplot:

 data(diamonds) diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut)) qplot(cut,carat,data = diamonds, geom = "boxplot") + coord_flip() 

在这里输入图像描述

现在超长的标题横向分布,很容易阅读!