将文本添加到绘图轴而不删除r中的现有轴标签

时间:2012-08-25 10:08:32

标签: r plot labels axes

我有以下情节

xleft<-c(1,2,3)
xright<-c(2,3,4)
ybottom<-c(1,2,3)
ytop<-c(2,3,4)

plot(c(1,4),c(1,4),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")
x.label<-c("Long species Name4","Long species Name5","Long species Name5")

我想将数字轴和轴标题留在原位。我还想添加一个传奇。所以最终产品看起来像这样

enter image description here

在不必使用

完全清除轴的情况下,最好的方法是什么
par(xaxt = "n", yaxt = "n")

并添加文字?谢谢你的建议。

2 个答案:

答案 0 :(得分:5)

我认为这样做的方法和R FAQ 7.27“如何创建旋转轴标签?”同意,是在边缘留出空间,然后添加长标签文本。

 mx=12
 my=12
 par(mar = c(mx,my, 4, 2) + 0.1)
 plot(c(1,4),c(1,4),type="n",main="title",xlab="site.x",ylab="ylab")
 rect(xleft,ybottom,xright,ytop,col=c("blue","red","green"))
 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)

您需要调整mxmy字符串的长度,也可以调整文本中的负偏移量以阻止它与标签冲突。另请注意使用xpd=TRUE来阻止绘图被剪裁到图形区域。这也是获得传奇的关键:

 par(xpd=TRUE)
 legend(locator(1),legend=c("Species A","Species B","Species C"),
                             fill=c("blue", "red", "green"))

然后点击您想要图例的位置 - 或将locator(1)替换为list(x=-0.7,y=0.6)

使用ggplot包可能会找到一种更简单的方法。

答案 1 :(得分:3)

@Spacedman的答案很棒,但我只想提供一个更新。他的代码(至少对我来说)在刻度标签上绘制了轴标签。要更改标签的位置,您需要查看par("mfg")。我认为以下代码可以或多或少地执行您想要的操作:

par(mai=c(2.5, 2.25, 0.82, 0.42), mgp=c(9, 1, 0))
plot(c(1,4), c(1,4), xaxp=c(1,4,3), yaxp=c(1,4,3), type="n", 
  main="title", xlab="site.x", ylab="ylab")
rect(xleft, ybottom, xright, ytop, col=c("blue","red","green"))
axis(1, at=x.label.position, labels=x.label, las=2)
axis(2, at=y.label.position, labels=y.label, las=2)
par(xpd=TRUE)
legend(x=0.25, y=0.75, 
  legend=c("Text", "Text", "Text"),
  fill=c("blue", "red", "green"),
  title="Legend")

产生以下图:

enter image description here

正如@Spacedman建议的那样,对ggplot2包中的边缘和轴的许多改变都比较简单(一旦你习惯了......)。