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

enter image description here

有帮助吗?

解决方案

将最后一行更改为

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

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

alt text

上图来自 这篇博客文章.

其他提示

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

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

利用 coord_flip()

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

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

enter image description here


在第3.9章 数据科学的R, ,威克汉姆和格罗蒙德谈到了这个确切的问题:

coord_flip() 切换X和Y轴。如果您想要水平箱形图,这很有用。这对于长标签也很有用:很难使它们适合而不重叠X轴。

我想提供一个替代解决方案,最新版本中需要一个类似于我即将提出的强大解决方案 格特恩, ,自从引入画布旋转功能以来。

基本上,您需要使用三角学确定相对位置,方法是构建一个返回一个函数 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)
}

坦率地说,在我看来,我认为应该提供“自动”选项 ggplot2 为了 hjustvjust 参数,当指定角度时,无论如何,让我们演示一下上面的工作原理。

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

产生以下结果:

Example

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)

通过github搜索相关参数名称找到: https://github.com/search?l=r&q=element_text+90+vjust+org%3Acran&type=code = code

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top