旋转并在GGPLOT2间隔轴标签(Rotating and spacing axis labels

2019-06-21 02:13发布

我有一个图,其中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))

Answer 1:

更改最后一行

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

默认情况下,当旋转轴在文本的中心对齐,甚至。 当旋转+/- 90度,你通常希望它在边缘,而不是对齐:

上面的图片是从这个博客帖子 。



Answer 2:

为了使在刻度标签完全可见,在同一方向为Y轴标签阅读文本,更改最后一行

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


Answer 3:

使用coord_flip()

在“R为数据科学,”韦翰和Grolemund这种确切的问题发言。 在第3.8章, 位置调整 ,他们写道:

coord_flip()切换x和y轴。 这是有用的(例如),如果你想水平盒形图。 它也是长标签有用:很难让他们不适合在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()

而现在的超长标题是水平铺开,很容易阅读!



Answer 4:

我想提供一个替代的解决方案,类似于我将提议中的最新版本是需要一个强大的解决方案ggtern ,因为引入了画布旋转功能。

基本上,需要使用三角学来确定相对位置,通过构建一个函数,它返回一个element_text对象,给定角度(即度)和定位(即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)
}

坦率地说,在我看来,我认为一个“自动”选项,应在提供ggplot2hjustvjust参数,指定角度时,无论如何,让演示如何上述作品。

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

这将产生以下:



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

由创建于2018年11月6日reprex包 (v0.2.1)

用GitHub上搜索相关的参数名发现: https://github.com/search?l=R&q=element_text+angle+90+vjust+org%3Acran&type=Code



文章来源: Rotating and spacing axis labels in ggplot2
标签: r ggplot2 labels