增加字符串标签值的轴标签空间

时间:2016-03-23 07:04:27

标签: r plot

我正在创建一个x轴包含字符串的图。我按照此posting的说明操作,并成功创建了以下图表:

myDf <- cbind(Row.Names=rownames(mtcars), mtcars)
plot(myDf$mpg, axes=F, xlab="Car", ylab="MPG")
axis(2)
axis(1, at=seq_along(myDf$mpg), labels=myDf$Row.Names, las=2, cex.axis=0.70)
box()

enter image description here

现在,问题是轴非常狭窄。如何增加绘图图像的x轴和底部之间的垂直空间?理想情况下,x轴值不会与x轴标签重叠(&#34; Car&#34;在本例中)。

1 个答案:

答案 0 :(得分:2)

我们需要在底部设置更大的利润。然后使用 mtext()添加x轴标签。

# set the margins 
par(mar = c(10, 4.1, 4.1, 2.1))

plot(myDf$mpg, axes=F, xlab="", ylab="MPG")
axis(2)
axis(1, at = seq_along(myDf$mpg), labels = myDf$Row.Names, las = 2, cex.axis = 0.70)
box()

# add xlabel, "line" arguement controls vertical position
mtext("Car", side = 1, line = 6)

enter image description here

使用 ggplot

library(ggplot2)
#my data
myDf <- cbind(car = rownames(mtcars), mtcars)
#to keep ordering as in data, set custom levels (default is alphabetical)
myDf$car <- factor(myDf$car, levels = myDf$car)

#plot
ggplot(myDf, aes(x = car, y =  mpg)) +
  geom_point() +
  # rotate car names by 90 degrees, adjust vertically and horizontally
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

enter image description here