2012-04-23 1204 views
60

我试图让x轴标签在barplot上旋转45度而没有运气。这是我有下面的代码:在R中为barplot旋转x轴标签

barplot(((data1[,1] - average)/average) * 100, 
     srt  = 45, 
     adj  = 1, 
     xpd  = TRUE, 
     names.arg = data1[,2], 
     col  = c("#3CA0D0"), 
     main  = "Best Lift Time to Vertical Drop Ratios of North American Resorts", 
     ylab  = "Normalized Difference", 
     yaxt  = 'n', 
     cex.names = 0.65, 
     cex.lab = 0.65) 

回答

45

EDITED ANSWER PER大卫的回应:

这里有一种hackish的方式。我猜测有一个更简单的方法。但是,您可以通过从barplot保存小节位置并上下稍微调整来抑制小节标签和小节的标签文字。下面是与mtcars数据集的例子:

x <- barplot(table(mtcars$cyl), xaxt="n") 
labs <- paste(names(table(mtcars$cyl)), "cylinders") 
text(cex=1, x=x-.25, y=-1.25, labs, xpd=TRUE, srt=45) 
+0

_caveat_:如果你使用的是'beside = TRUE',如果你只需要每个组一个标签,你可能会想用'colMeans(x)'而不是'x'。 – MichaelChirico 2016-10-07 03:59:34

23

如果你想旋转与角度等于或小于90 x轴标签,请尝试以下方法:

它使用barplot的说法space=1使列的宽度等于列的间隔空间。

通过这种方式,我们可以调整由Tyler Rinker的答案根据@BenBarnes指定的R FAQ中提供的代码。

par(mar = c(7, 4, 2, 2) + 0.2) #add room for the rotated labels 

#use mtcars dataset to produce a barplot with qsec colum information 
mtcars = mtcars[with(mtcars, order(-qsec)), ] #order mtcars data set by column "qsec" (source: http://stackoverflow.com/questions/1296646/how-to-sort-a-dataframe-by-columns-in-r) 

end_point = 0.5 + nrow(mtcars) + nrow(mtcars)-1 #this is the line which does the trick (together with barplot "space = 1" parameter) 

barplot(mtcars$qsec, col="grey50", 
     main="", 
     ylab="mtcars - qsec", ylim=c(0,5+max(mtcars$qsec)), 
     xlab = "", 
     space=1) 
#rotate 60 degrees, srt=60 
text(seq(1.5,end_point,by=2), par("usr")[3]-0.25, 
    srt = 60, adj= 1, xpd = TRUE, 
    labels = paste(rownames(mtcars)), cex=0.65) 

enter image description here

154

使用可选参数拉斯= 2。

barplot(mytable,main="Car makes",ylab="Freqency",xlab="make",las=2) 

enter image description here

+0

绝对可行。谢谢 – 2016-04-21 09:03:47

+1

我相信这应该是被接受的答案。完美地使用问题中使用的基本barplot函数的参数。 – jwhaley58 2016-11-08 15:06:27

+0

同意,这应该是被接受的答案。更简洁的解决方案 – snlan 2017-02-01 13:30:59

1

安德烈·席尔瓦的回答伟大工程,对我来说,与在 “barplot” 行一个警告:

barplot(mtcars$qsec, col="grey50", 
    main="", 
    ylab="mtcars - qsec", ylim=c(0,5+max(mtcars$qsec)), 
    xlab = "", 
    xaxt = "n", 
    space=1) 

的通知 “xaxt” 的说法。如果没有它,标签会第一次没有60度的旋转。

0

您只需将您的数据帧分为以下功能

rotate_x <- function(data, column_to_plot, labels_vec, rot_angle) { 
    plt <- barplot(data[[column_to_plot]], col='steelblue', xaxt="n") 
    text(plt, par("usr")[3], labels = labels_vec, srt = rot_angle, adj = c(1.1,1.1), xpd = TRUE, cex=0.6) 
} 

用法:

rotate_x(mtcars, 'mpg', row.names(mtcars), 45) 

enter image description here

您可以更改的旋转角度标签如所须。