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

相關文章
相關標籤/搜索