I would like to create such a diagram in r:
I have a such matrix
[1] [2] [3] [4] [5] .... [30]
[1] 0.5 0.75 1.5 0.25 2.5 .... 0.51
[1] 0.84 0.24 3.5 0.85 0.25.... 1.75
[1] 0.35 4.2 0.52 1.5 0.35.... 0.75
.
. .......................................
.
[30]0.84 1.24 0.55 1.5 0.85.... 2.75
and I want to have a diagram,
Is there any packages or method in r to do this job? how can I do that?
to plot this, you need three data points:
x, y, color
Thus, first step is reshaping.
Fortunately, matricies are already a vector, simply with a dimension attribute, so we just need to create a data.frame of x,y coordinates. We do this with expand.grid
.
# create sample data.
mat <- matrix(round(runif(900-30, 0, 5),2), 30)
create the (x, y) data.frame.
Notice that y
is the seq of rows and x
the seq of columns
dat <- expand.grid(y=seq(nrow(mat)), x=seq(ncol(mat)))
## add in the values from the matrix.
dat <- data.frame(dat, value=as.vector(mat))
## Create a column with the appropriate colors based on the value.
dat$color <- cut( dat$value,
breaks=c(-Inf, 1, 2, Inf),
labels=c("green", "yellow", "red")
)
## Plotting
library(ggplot2)
ggplot(data=dat, aes(x=x, y=y)) + geom_point(color=dat$color, size=7)
If your data is a result of correlation, then corrplot package can be useful.
The corrplot package is a graphical display of a correlation matrix, confidence interval. It also contains some algorithms to do matrix reordering. In addition, corrplot is good at details, including choosing color, text labels, color labels, layout, etc.
Example plot based on @RicardoSaporta sample data.
library(corrplot)
#sample data
mat <- matrix(round(runif(900, 0, 5),2), 30)
#plot
corrplot(mat, is.corr = FALSE)
Additionally, you could have used simply the base function image
:
mat <- matrix(round(runif(900-30, 0, 5),2), 30)
image(mat,
breaks=c(min(mat),1,2,max(mat)), #image can't handle Inf but that's not a problem here
col=c("green","yellow","red"), axes=FALSE)
Or if you prefer dots instead of cells:
grid <- expand.grid(1:nrow(mat),1:ncol(mat)) #Same two steps as in Ricardo Sapporta answer
category <- cut(mat,c(-Inf,1,2,Inf))
plot(grid, #Then plot using base plot
col=c("green","yellow","red")[category], #here is the trick
pch=19, cex=2, axes=FALSE) #You can customize it as you wish
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With