【问题标题】:Remove spacing around plotting area in r删除r中绘图区域周围的间距
【发布时间】:2012-08-31 07:19:40
【问题描述】:

当我创建以下绘图时,我在绘图区域和轴之间得到了不需要的空间(即蓝色框和 x 轴之间的空白区域。如何删除这个空间并使绘图区域与绘图轴齐平? 谢谢。

xleft<-c(1,2,2.5)
xright<-c(2,2.5,2.75)
ybottom<-c(1,2,2.5)
ytop<-c(2,2.5,2.75)

par(mar = c(15,15,2.75,2.75) + 0.1)
plot(c(1,2.75),c(1,2.75),type="n",main="title",xlab="site.x",ylab="ylab")
rect(xleft,ybottom,xright,ytop,col=c("blue","red","green"))

#Label position along  axes
x.label.position<-(xleft+xright)/2
y.label.position<-(ybottom+ytop)/2

 #Labels
 x.label<-c("Long species Name1","Long species Name2","Long species Name3")
 y.label<-c("Long species Name4","Long species Name5","Long species Name5")

 text(par()$usr[1]-0.5,y.label.position,y.label,xpd=TRUE,adj=1)
 text(y=par()$usr[3]-0.5,x=x.label.position,x.label,xpd=TRUE,adj=1,srt=90)

 par(xpd=TRUE)
 legend(-0.1,0,legend=c("Species A","Species B","Species C"),fill=c("blue", "red", "green"))

更新 我用我的实际数据尝试了 plannapus 的建议,但只能让 y 轴表现出来,这段代码中是否还有其他一些东西在绘图区域的两侧增加了空间?

quartz("colour.plot")
par(mar=c(15,15,4,2)+0.1)#sets margins of plotting area

#create the data plot
    plot(c(0,100), c(0,100), type = "n", main = paste(x,"vs",y," -",depth),xlab=paste("Species composition in remainder ",x),ylab=paste("Species composition in remainder ",y),asp=1,xaxs="i",yaxs="i")

#Add the rectangles
rect(mdf$xleft,mdf$ybottom,mdf$xright,mdf$ytop,col=mdf$colour)

生产

【问题讨论】:

  • "在这段代码中是否还有一些其他的东西在绘图区域的两侧增加了空间?"是的:asp=1。这样,您将强制 x 轴和 y 轴相等,这可能与您的绘图区域的大小冲突。
  • 在调用plot 之前添加par(pty="s") 应该会强制绘图区域为正方形(因此"s")而不是图像上的矩形,因此更正asp“故障"。
  • 我认为您应该选择@plannapus 答案,或者简单地设置xlimylim 以匹配您要绘制的区域。尽管@Alan 的解决方案给出了正确的外观,但对于您想要在这里执行的操作而言,概念上并不正确。只能说“治标不治本”。

标签: r plot


【解决方案1】:
plot(c(1,2.75),c(1,2.75),type="n",main="title",xlab="site.x",ylab="ylab",axes=F) # ann
axis(1,pos=1)
axis(2,pos=1)

所有轴都被删除,然后您可以将新轴添加到您想要的pos

【讨论】:

  • 它确实可以正常工作,但需要注意的是,此解决方案移动了轴但不会修改绘图区域。
【解决方案2】:

函数 plot 中有一个参数可以处理:xaxs(以及 y 轴的 yaxs)。 默认情况下,它设置为xaxs="r",这意味着每侧保留 4% 的轴值。要将其设置为 0:xaxs="i"。有关详细信息,请参阅 ?par 中的 xaxs 部分。

plot(c(1,2.75),c(1,2.75),type="n",main="title",xlab="site.x",ylab="ylab", xaxs="i", yaxs="i")
rect(xleft,ybottom,xright,ytop,col=c("blue","red","green"))

【讨论】:

  • @planapus 我想使用您的解决方案,但我遇到了麻烦,因为我使用的是 asp=1,它会在您的解决方案中为 x 轴的两侧增加空间(请参阅相关更新下的示例) .有没有办法避免这个问题?
  • @Elizabeth 您是否按照我在上面 cmets 中的建议尝试了 par(pty="s")? (理想情况下,虽然解决方案是准确定义绘图区域的大小,但这样做很痛苦)
  • 我做了,但只是注意到我在那行有一个错误。已修复,现在可以使用。谢谢:)
  • 很酷的功能!以前不知道axis(..., pos),但由于它在绘图区域内绘制轴而不是调整它,我怀疑this is what it is intended for
猜你喜欢
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 2021-12-23
  • 2020-08-30
  • 2020-10-19
  • 1970-01-01
相关资源
最近更新 更多