R

时间:2016-01-15 17:20:50

标签: r plot

我必须在R中绘制以下图表:

library(TTR)
x.date<-seq(1,num.years,by=20)
x.axis<-list(x1="1900",x2="1920",x3="1940",x4="1960",x5="1980",x6="2000")
plot(Annual.Mean.1, type="l",col="gray48",xaxt="n", xlab="Years",
 ylab="Temperature")
grid()
axis(1,x.date,x.axis)
SMA.1<-SMA(Annual.Mean.1,n=10
par(new=TRUE)
lines(SMA.1,col="red",type="l",lwd="2",xaxt="n",yaxt="n",ann=FALSE)
SMA.2<-SMA(Annual.Mean.1,n=15)
par(new=TRUE)
lines(SMA.2,col="mediumpurple",type="l",lwd="2",xaxt="n",yaxt="n",ann=FALSE)
SMA.3<-SMA(Annual.Mean.1,n=20)
lines(SMA.3,col="blue",type="l",lwd="2",xaxt="n",yaxt="n",ann=FALSE)
legend("topleft",legend=c("Average Temperature","SMA 10 years","SMA 15 years","SMA 20 Years"),
   text.col=c("black","red","mediumpurple","blue"),col=c("gray48","red","mediumpurple","blue"),
   cex=0.7,lty=c(1,1,1,1))

输出是这样的: enter image description here

在上图中,包含图例的矩形非常大;我想获得一个较小的矩形,如下图所示:

enter image description here

怎么做?

更新

正如评论中所建议的那样,我修改了我的代码,以便让任何人都可以重现:

library(TTR)
set.seed(1)
x.date<-seq(1,111,by=20)
x.axis<-list(x1="1900",x2="1920",x3="1940",x4="1960",x5="1980",x6="2000")
data<-runif(111,-3,3)
plot(data, type="l",col="gray48",xaxt="n",xlab="Years",
ylab="Temperature")
grid()
axis(1,x.date,x.axis)
SMA.1<-SMA(data,n=10)
par(new=TRUE)
lines(SMA.1,col="red",type="l",lwd="2",xaxt="n",yaxt="n",ann=FALSE)
SMA.2<-SMA(data,n=15)
par(new=TRUE)
lines(SMA.2,col="mediumpurple",type="l",lwd="2",xaxt="n",yaxt="n",ann=FALSE)
SMA.3<-SMA(data,n=20)
lines(SMA.3,col="blue",type="l",lwd="2",xaxt="n",yaxt="n",ann=FALSE)
legend("topleft",legend=c("Average Temperature","SMA 10 years","SMA 15 years","SMA 20 Years"),
   text.col=c("black","red","mediumpurple","blue"),col=c("gray48","red","mediumpurple","blue"),
   cex=0.7,lty=c(1,1,1,1))

我仍然遇到与上述相同的问题。

1 个答案:

答案 0 :(得分:0)

降低cex来电中legend参数的值。你可以在cex=0.7获得它。尝试0.6或0.5(或更低),直到找到最佳尺寸。

如果这不起作用,另一种方法是使用参数bty = "n"完全删除图例周围的框。如果图例的背景阻挡了图表中的线条,请在代码中向上移动legend命令,以便首先绘制它并在其上方绘制线条。