Is there a straightforward way to get the RGB composition of a plot in R?
Right now what I am doing is writing the plot to an external file, then reading it with readPNG
from the png
package. I haven't found anything yet but surely there must be a better way to do this.
[EDIT] the codes:
INPUT <- c("3
0 1 3 3
2 2 6 4
1 0 3 5")
require(png)
# This is the pixel precision, 1e4 recommended for optimal results
PRECISION <- 1e4
# Just parsing the initial input and the vectors
sdata <- strsplit(gsub("\n", " ", INPUT), split=c(" "))[[1]]
data <- as.numeric(sdata)
# Some usefull matrices for the plot points
Rm <- matrix(data[-1], data[1],4,T)
Rmx <- cbind(Rm[,c(1,1)], Rm[,c(3,3)], Rm[,1])
Rmy <- cbind(Rm[,c(2,4)], Rm[,c(4,2)], Rm[,2])
# and for the overall big rectangle
B <- c(min(Rm[,1]), min(Rm[,2]), max(Rm[,3]), max(Rm[,4]))
Bx <- c(B[c(1,1)],B[c(3,3)],B[1])
By <- c(B[c(2,4)],B[c(4,2)],B[2])
A <- B[3:4]-B[1:2]
# Biggest number of digits given, not perfect but it works
D <- max(nchar(gsub("(.*\\.)|([0]*$)", "", sdata[-1])))
# Create the plot and save it in the working directory,
# then read it back to get the RGB information
png("rgb1.png", bg="black", width=PRECISION, height=PRECISION)
plot(x=Rmx, y=Rmy,'n', xaxt='n', yaxt='n', xlab="", ylab="", bty='n',
xlim=B[c(1,3)], ylim=B[c(2,4)])
polygon(Bx, By, col="blue", border=NA)
sapply(1:nrow(Rm), function(v){ polygon(Rmx[v,], Rmy[v,],
col="red", border=NA)})
dev.off()
plot.rgb <- readPNG("rgb1.png")
# Compute area
Re <- sum(plot.rgb[,,1])
Bl <- sum(plot.rgb[,,3])
round( (Re/(Bl+Re))*prod(A), digits=D+1 )