Question

I do not have much experience in R, and I wonder if they can help me in this situation.

I have the following matrix:

mat <- matrix(c(0,0.5,0.2,0.23,0.6,0,0,0.4,
         0.56,0.37,0,0.32,0.4,0.99,0.54,0.6,0,0.39), ncol=6, nrow=3)

dimnames(mat) = list( 
                  c("y1","y2","y3"),
                  c("day1","day2","day3","day4","day5","day6")
                    )

> mat
   day1 day2 day3 day4 day5 day6
y1  0.0 0.23 0.00 0.37 0.40 0.60
y2  0.5 0.60 0.40 0.00 0.99 0.00
y3  0.2 0.00 0.56 0.32 0.54 0.39
> 

I want to know how can I get a graph where points would be marked based on the matrix.

The values ​​are arbitrary in the interval [0,1]. It is possible to change the color of the generated points as a set of constraints?

Example:

  • (0,0.2] - Red
  • (0.2,0.4] - Green
  • (0.4,0.6] - Yellow
  • (0.6,0.9] - Blue
  • (0.9,1] - Black

I apologize if I have not explained myself well.

Thank you!

Was it helpful?

Solution 2

If you just want coloured points, something like this will do it:

palette(c("red","green","yellow","blue","black"))
plot.default(
  as.data.frame.table(t(mat))[1:2],
  col=findInterval(t(mat),c(0,0.2,0.4,0.6,0.9)),
  pch=19,
  axes=FALSE,ann=FALSE,
  panel.first=grid()
)
axis(2,at=1:length(rownames(mat)),labels=rownames(mat),lwd=0,lwd.ticks=1,las=1)
axis(1,at=1:length(colnames(mat)),labels=colnames(mat),lwd=0,lwd.ticks=1)
box()
palette("default")

Result:

enter image description here

OTHER TIPS

Assuming that your range for yellow should be [0.4,0.6] (otherwise you haven't specified a colour for (0.4,0.5) - you need to even if your data doesn't require it)

image(mat,col=c("red","green","yellow","blue","black"),breaks=c(0,0.2,0.4,0.6,0.9,1))

I've ignored the interval endpoint issue.

To assign colours to the different intervals, you can break up your values into groups using cut. Like others have said, it's a bit unclear what to do with points on the boundaries, so I've set include.lower to TRUE:

library(reshape2)
df = melt(mat)
colnames(df)[1:2] = c('year', 'day')
df$value_groups = cut(df$value, breaks=c(0,0.2,0.4,0.6,0.9,1), include.lower=TRUE)

library(ggplot2)
ggplot(df, aes(x=day, y=value, colour=value_groups, shape=year)) +
  geom_point(size=3)

Result:

enter image description here

Here is how I would do it using lattice:

library(reshape2)
library(lattice)

mmat <- melt(mat) # reshaping the data

# note that zero isn't included in the interval
  mmat$colors <- cut(mmat$value, breaks=seq(0, 1, 0.2), include.lower=TRUE) # stealing from Marius


xyplot(value ~ Var2 | Var1, mmat, groups = colors,
  par.settings = list(superpose.symbol = 
    list(col = c('red', 'green', 'yellow', 'blue', 'black'))))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top