【问题标题】:R: Adjust spacing between ticks on barplotR:调整条形图上刻度之间的间距
【发布时间】:2021-04-05 03:50:19
【问题描述】:

我需要重新创建一个使用 R 生成并随后使用 Inkscape 编辑的图表。我想在 R 中做尽可能多的事情。这是图表:

图表中的一些文本标签我稍后将使用 Inkscape 添加。我的问题在于蜱虫。我决定使用没有轴的 barplot() 并将它们与 axis() 分开添加。如您所见,条形之间有间距。我只是不知道如何为 x 轴上的刻度设置间距,以便使用条形调整它们。现在蜱虫正在从中心脱落。这是我的代码:

mwe <- data.frame(month=c("Dec 2007", "Jan 2008", "Feb 2008", "Mar 2008","Apr 2008","May 2008","Jun 2008"),
                 job_difference_in_thousands=c(70, -10, -50, -33, -149, -231, -193),
                 color=c("darkred","darkred","darkred","darkred","darkred","darkred","darkred"))
                 
barplot(height=mwe$job_difference_in_thousands,
        axes=F,
        col=mwe$color,
        border = NA,
        space=0.1,
        main="Grafik X_1 NEW JOBS IN THE UNITED STATES",
        cex.main=0.75,
        ylim=c(-800,600),
)
axis(1,pos=0, lwd.tick=0, labels=F,line=1, outer=TRUE)
axis(1,at=0:6+0.5,labels=FALSE,lwd=0,lwd.tick=1)
axis(1, at=0:6+0.5,
     labels=mwe$month,
     cex.axis=0.65,
     lwd=0)
axis(2, at=seq(-800,600,by=200),las=2,cex.axis=0.65, lwd=0, lwd.tick=1)

reprex package (v0.3.0) 于 2020 年 12 月 28 日创建

【问题讨论】:

  • 有什么理由使用 base R 而不是 ggplot2?
  • 在原始图表中也使用了基础 R。你认为使用 ggplot2 会更容易吗?
  • 更简单! ggplot2 有一个名为scale_x_discrete(expand = ...) 的东西,它完全符合您的要求。即使从长远来看,让自己熟悉 ggplot2 也会更好,因为它使用起来非常简单,而且它周围有很多社区。​​span>
  • 我之前使用过 ggplot2 并没有发现它真的很直观。但我会再看看它。
  • 这可能会有所帮助:r-graph-gallery.com

标签: r bar-chart xticks


【解决方案1】:

当您调用 barplot.R 时,R 会返回条形中点的位置。因此,只需存储 barplot 的返回值并将其用作刻度位置的中心。

mwe <- data.frame(month=c("Dec 2007", "Jan 2008", "Feb 2008", "Mar 2008","Apr 2008","May 2008","Jun 2008"),
                 job_difference_in_thousands=c(70, -10, -50, -33, -149, -231, -193),
                 color=c("darkred","darkred","darkred","darkred","darkred","darkred","darkred"))
                 
bar_pos <- barplot(height=mwe$job_difference_in_thousands,
        axes=F,
        col=mwe$color,
        border = NA,
        space=0.1,
        main="Grafik X_1 NEW JOBS IN THE UNITED STATES",
        cex.main=0.75,
        ylim=c(-800,600),
)
axis(1,pos=0, lwd.tick=0, labels=F,line=1, outer=TRUE)
axis(1,at=bar_pos,labels=FALSE,lwd=0,lwd.tick=1)
axis(1, at=bar_pos,
     labels=mwe$month,
     cex.axis=0.65,
     lwd=0)
axis(2, at=seq(-800,600,by=200),las=2,cex.axis=0.65, lwd=0, lwd.tick=1)

【讨论】:

  • 为了完整性,如果您只希望每第 n 个刻度上的标签,它的工作原理是这样的(在本例中 n=2):axis(1,at=bar_pos[seq(1,length(bar_pos ),2)], 标签=mwe$month[seq(1,7,2)], cex.axis=0.65, lwd=0)
  • 您可以使用以下命令在 x 轴刻度的标签中获取换行符:labels=sub("\\s","\n",mwe$month[seq(1,7 ,2)])