R

时间:2019-07-09 07:35:25

标签: r plot histogram legend

我需要将图例放在图片标题下,但我不知道如何轻松完成

par(mfrow=c(2,3),oma=c(0,0,0,0),xpd=NA)
maximo<-max(valuetable[,-ncol(valuetable)],na.rm = T )
c1<-which(data$class==1);cluster1 <- data[c1,]
c2<-which(data$class==2);cluster2 <- data[c2,]
c3<-which(data$class==3);cluster3 <- data[c3,]
c4<-which(data$class==4);cluster4 <- data[c4,]
c5<-which(data$class==5);cluster5 <- data[c5,]
hist(as.matrix(cluster1[,-ncol(cluster1)]),ylab="Frecuencia",xlab="Precipitación (mm)",ylim=c(0,3000), xlim=c(0,maximo),col=Set1T[1],main="");box()
hist(as.matrix(cluster2[,-ncol(cluster2)]),ylab="Frecuencia",xlab="Precipitación (mm)",ylim=c(0,3000), xlim=c(0,maximo),col=Set1T[2],main="");box()
hist(as.matrix(cluster3[,-ncol(cluster3)]),ylab="Frecuencia",xlab="Precipitación (mm)",ylim=c(0,3000), xlim=c(0,maximo),col=Set1T[3],main="");box()
hist(as.matrix(cluster4[,-ncol(cluster4)]),ylab="Frecuencia",xlab="Precipitación (mm)",ylim=c(0,3000), xlim=c(0,maximo),col=Set1T[4],main="");box()
hist(as.matrix(cluster5[,-ncol(cluster5)]),ylab="Frecuencia",xlab="Precipitación (mm)",ylim=c(0,3000), xlim=c(0,maximo),col=Set1T[5],main="");box()
mtext("Histogramas de Precipitación", side = 3, line = -1.5, outer = TRUE)
legend("top",legend=c("Cluster 1", "Cluster 2","Cluster 3","Cluster 4","Cluster 5"),col = 1:5, lty=1,horiz = T,lwd=3, bty = "n", cex = 1.3)

enter image description here

1 个答案:

答案 0 :(得分:0)

代替指定“ top”作为legend()的第一个参数,而是如下所示放置两个数字(第一个表示“ x”位置,第二个表示“ y”位置)。 legend()的前两个参数是x和y。

legend(-0.5, 62, legend=c("Cluster 1", "Cluster 2","Cluster 3","Cluster 4","Cluster 5"),col = 1:5, lty=1,horiz = T,lwd=3, bty = "n", cex = 1.3)

这将产生以下结果: enter image description here

您可能只需要稍微打一点数字就可以使它看起来不错。


完美复制示例图的整个代码是:

data(mtcars)
data <- mtcars

par(mfrow = c(2, 3), oma = c(0, 0, 3, 0), xpd = NA)

hist(mtcars$vs)
hist(mtcars$vs)
hist(mtcars$vs)
hist(mtcars$vs)
hist(mtcars$vs)

mtext("Histogramas de Precipitación", side = 3, outer = T)

legend (
    x = -0.5, y = 62, # these two parameters are the relevant ones
    legend = c("Cluster 1", "Cluster 2", "Cluster 3", "Cluster 4", "Cluster 5"),
    col = 1:5, 
    lty = 1,
    horiz = T,
    lwd = 3, 
    bty = "n",
    cex = 1.3
)


编辑是因为我最初误解了问题。