旋转 x 轴标签在 R 为条形图

我试图得到的 x 轴标签旋转45度在一个条形图没有运气。下面是我的代码:

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)
343626 次浏览

EDITED ANSWER PER DAVID'S RESPONSE:

这是一种黑客的方式。我想还有更简单的办法。但是您可以通过保存 barplot中的条形图位置来抑制条形图标签和标签的图文,并进行一些向上和向下的调整。下面是一个关于 mtcar 数据集的例子:

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)

使用基础图形旋转角度等于或小于90度的 x 轴标签。改编自 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"


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 = "",
xaxt = "n", # Do not plot the default labels
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

你可以用

par(las=2) # make label text perpendicular to axis

这里写着: http://www.statmethods.net/graphs/bar.html

使用可选参数 las = 2。

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

enter image description here

安德烈•席尔瓦(Andre Silva)的回答对我很有用,但有一点需要注意:

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

注意“ xaxt”参数。没有它,标签将被绘制两次,第一次没有60度旋转。

您只需将数据帧传递到以下 功能:

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

Usage:

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

enter image description here

您可以根据需要更改标签的 旋转角度旋转角度

您可以使用 ggplot2旋转 x 轴标签,添加一个额外的层

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

在 Bar Plot 的文档中,我们可以读到可以传递给函数调用的附加参数(...) :

...    arguments to be passed to/from other methods. For the default method these can
include further arguments (such as axes, asp and main) and graphical
parameters (see par) which are passed to plot.window(), title() and axis.

在图形参数的文档(par的文档)中,我们可以看到:

las
numeric in {0,1,2,3}; the style of axis labels.


0:
always parallel to the axis [default],


1:
always horizontal,


2:
always perpendicular to the axis,


3:
always vertical.


Also supported by mtext. Note that string/character rotation via argument srt to par does not affect the axis labels.

这就是为什么传递 las=2使标签 垂直,虽然不是在45 °