【问题标题】:Increase axis label space for string label values增加字符串标签值的轴标签空间
【发布时间】:2016-07-10 08:42:55
【问题描述】:

我正在创建一个 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()

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

【问题讨论】:

    标签: r plot


    【解决方案1】:

    我们需要在底部设置更宽的边距。然后使用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)
    

    使用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))
    

    【讨论】:

    • 谢谢。有没有办法以编程方式而不是通过反复试验来确定边距(和文本“行”参数)?
    • @stackoverflowuser2010 我不知道。为什么不使用 ggplot?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 2017-02-05
    相关资源
    最近更新 更多