如何使用多个条形图添加图例?

时间:2015-09-04 13:25:01

标签: r

我的代码:

#!/usr/bin/R

par(mfrow=c(4,1))

fcm <-c(13.0,12.5,11.8)
gk  <-c(10.9 ,   10.5  ,  10.2)
gg  <-c(12.0 ,   11.0 ,   10.8)
data1 <- rbind(fcm,gk,gg)
colnames(data1) <- c(5,6,7)

fcm <-c(1.29,1.25,1.22)
gk  <-c(1.19,1.05,1.00)
gg  <-c(1.10,1.02,1.07)
data2 <- rbind(fcm,gk,gg)
colnames(data2) <- c(5,6,7)

fcm <-c(10.5,9.8,8.8)
gk  <-c(11.0,8.4,10.0)
gg  <-c(2.0,1.8,1.6)
data3 <- rbind(fcm,gk,gg)
colnames(data3) <- c(5,6,7)

fcm <-c(0.33,0.29,0.31)
gk  <-c(0.49,0.40,0.35)
data4 <- rbind(fcm,gk)
colnames(data4) <- c(5,6,7)

barplot(as.matrix(data1),ylim=c(0,20),main="P wave",
        xlab="number of clusters", ylab="traveltime rms(ms)",
        col=c("red", "black", "green"), beside=TRUE)
barplot(as.matrix(data2),ylim=c(0,2),main="MT",
        xlab="number of clusters", ylab="MT functions",
        col=c("red", "black", "green"), beside=TRUE)
barplot(as.matrix(data3),ylim=c(0,20),main="XBI",
        xlab="number of clusters", ylab="index value",
        col=c("red", "black", "green"), beside=TRUE)
barplot(as.matrix(data4),ylim=c(0,0.6),main="NCE",
        xlab="number of clusters", ylab="index value",
        col=c("red", "black"), beside=TRUE)

legend(legend = c("fcm","gk","gg"), fill = c( "red", "black", "green"))

dev.copy(png,"dp.png",width=9,height=6,units="in",res=200)
dev.off()

我已尝试将图例作为右上角,但它与图像重叠。任何人都知道如何添加图例,位置不是那么重要只是为了可见。我将此提交给科学期刊我需要一个不错的布局。

1 个答案:

答案 0 :(得分:1)

您可以使用layout代替par(mfrow...),然后将图例添加到您想要的位置。我让你的每个主要图块占据两行,而图例则是底部的一行。

此示例将图例水平放置在底部。不幸的是,由于我在防火墙后面,我无法上传图像。

layout(matrix(c(1, 1, 2, 2, 3, 3, 4, 4, 5), ncol=1))

# main plots
par(mai=rep(0.5, 4))
fcm <-c(13.0,12.5,11.8)
gk  <-c(10.9 ,   10.5  ,  10.2)
gg  <-c(12.0 ,   11.0 ,   10.8)
data1 <- rbind(fcm,gk,gg)
colnames(data1) <- c(5,6,7)

fcm <-c(1.29,1.25,1.22)
gk  <-c(1.19,1.05,1.00)
gg  <-c(1.10,1.02,1.07)
data2 <- rbind(fcm,gk,gg)
colnames(data2) <- c(5,6,7)

fcm <-c(10.5,9.8,8.8)
gk  <-c(11.0,8.4,10.0)
gg  <-c(2.0,1.8,1.6)
data3 <- rbind(fcm,gk,gg)
colnames(data3) <- c(5,6,7)

fcm <-c(0.33,0.29,0.31)
gk  <-c(0.49,0.40,0.35)
data4 <- rbind(fcm,gk)
colnames(data4) <- c(5,6,7)

barplot(as.matrix(data1),ylim=c(0,20),main="P wave",
        xlab="number of clusters", ylab="traveltime rms(ms)",
       col=c("red", "black", "green"), beside=TRUE)
barplot(as.matrix(data2),ylim=c(0,2),main="MT",
        xlab="number of clusters", ylab="MT functions",
        col=c("red", "black", "green"), beside=TRUE)
barplot(as.matrix(data3),ylim=c(0,20),main="XBI",
        xlab="number of clusters", ylab="index value",
        col=c("red", "black", "green"), beside=TRUE)
barplot(as.matrix(data4),ylim=c(0,0.6),main="NCE",
        xlab="number of clusters", ylab="index value",
        col=c("red", "black"), beside=TRUE)

# legend for blank plot
par(mai=c(0,0,0,0))
plot.new()
legend(legend = c("fcm","gk","gg"), fill = c( "red", "black", "green"), 
    "center", horiz=TRUE)

Output plot with xlab showing