ggplot2中的旋转和间隔轴标签

我有一个图,其中x轴是标签长的一个因素。 虽然可能不是理想的可视化效果,但如今我想简单地将这些标签旋转为垂直。 我已经用下面的代码弄清楚了这部分,可是如您所见,标签并不彻底可见。 html

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))

在此处输入图片说明


#1楼

将最后一行更改成 git

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

默认状况下,即便旋转,轴也将在文本中心对齐。 当您旋转+/- 90度时,一般但愿它在边缘对齐: github

替代文字

上面的图片来自此博客文章app


#2楼

我想提供一个替代解决方案,由于引入了画布旋转功能,因此在最新版本的ggtern中须要与我将要提出的功能相似的健壮解决方案。 ide

基本上,您须要使用三角函数来肯定相对位置,方法是构建一个函数,该函数返回element_text对象,并给出角度(即度)和位置(即x,y,top或right之一)信息。 函数

#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)
}

坦率地说,我认为应该在ggplot2hjustvjust参数提供“自动”选项,不管如何,当指定角度时,让咱们演示一下上面的工做原理。 ui

#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)

产生如下内容: spa

例


#3楼

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

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

#4楼

使用coord_flip()

data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))

qplot(cut,carat,data = diamonds, geom = "boxplot") +
  coord_flip()

在此处输入图片说明


数据科学R的第3.9章中,Wickham和Grolemund谈到了这个确切的问题: htm

coord_flip()切换x和y轴。 若是要水平框线图,这颇有用(例如)。 这对于长标签也颇有用:在不重叠x轴的状况下很难使其适应。


#5楼

ggpubr软件包提供了一个快捷方式,该快捷方式默认状况下会执行正确的操做(将文本右对齐,将文本中间对齐以打勾):

library(ggplot2)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))
q <- qplot(cut, carat, data = diamonds, geom = "boxplot")
q + ggpubr::rotate_x_text()

reprex软件包 (v0.2.1)建立于2018-11-06

经过GitHub搜索找到了相关的参数名称: https : //github.com/search?l=R&q= element_text+angle+90+vjust+org%3Acran&type =Code

相关文章
相关标签/搜索