I’ve clustered some values using K-means clustering. I plot three graphs and I would like a legend for the 3rd graph. I used the lengend() function to plot a legend, but the legend does not appear in the plot (see image) and no errors are reported.
library(cluster)
library(MASS)
par(mfrow=c(1,3))
par(oma=c(5,0,3,0))
dat <- read.table("representative_for_r.txt", header=TRUE)
data.p <- as.matrix(dat$Average_RMSD)
# Determine number of clusters
wss <- (nrow(data.p)-1)*sum(apply(data.p,2,var))
for (i in 2:15) wss[i] <- sum(kmeans(data.p,centers=i)$withinss)
plot(1:15, wss, type="b", xlab="Number of Clusters",ylab="Within groups sum of squares")
# K-Means Cluster Analysis
fit <- kmeans(data.p, 6) # 6 cluster solution
# get cluster means
aggregate(data.p,by=list(fit$cluster),FUN=mean)
# append cluster assignment
data.p <- data.frame(data.p, fit$cluster)
# PLot Clusters
clusplot(data.p, fit$cluster, color=TRUE, shade=TRUE, labels=2, lines=0)
data.p <- data.frame(dat$PDB, data.p)
#print(data.p)
plot(data.p[,2],col=data.p$fit.cluster) # takes the RMSD column of data.p(by indexing) then colours the points defined by the clustering
par(xpd=NA)
legend(0,0, c("Group 1","Group 2", "Group 3", "Group 4", "Group 5", "Group 6", "Group 7"), pch=1, col=1:7)
write.matrix(data.p, file = "kmeans_output.txt", sep = " ")
The output looks like:

I have tried the changing the X and Y values with the following:
200,200
-200,200
200,-200
-200,-200
Try:
Notice the scale on the
yaxis. The second coordinate you pass tolegend()must reside within the confines of the plot.0and both of-200and200are (way) beyond the limits of figure 3.If you don’t want to guess these things, the usage of a character to define placement is much more intuitive. See
?legendfor details on the character locations that can be supplied.