0
votes

I have a function :

f <- function(x,y){ return (x + y)}

I have to make a plot 2 D (not 3 D) with on the X and Y aes c(30:200). So I have to map both the x and the y to the function and based on the result of that function I have to color the point f(xi,yi) > ? and so on. How would I achieve this ?

I tried :

range <- c(30:200)
ys = matrix(nrow = 171,ncol = 171 )
for (i in range){

  for (y in range){
    ys[i-29,y-29] <- f(i,y) # exemple if f(i,j) < 0.5 color (i,j) red 


  }
}

df <- data.frame(x= c(30:200), y= c(30:200))

Now the x and y axes are correct however how would I be able to plot this since I cant just bind ys to the y axes. Using a ys seems like it isnt the right way to achieve this, how would I do this

Thx for the help

1
Please consider using a real R function, as return double is not valid R code. (If you're just indicating that your function returns some numeric, that's fine ... just do that. Having intentionally-invalid or incomplete R code makes it difficult to narrow down where you are having difficulty.)r2evans
done , put in a random function because the real 1 is kinda complicatedswaffelay
Understood, thanks. Your ys is a matrix with 171 rows and columns ... how do those values correlate with df's 171 rows? What is the purpose of df? Are you hoping to generate a heatmap from ys?r2evans
yes, some kind of heat map, based on the x,y coordinate i put a color on that spot if f(x,y) > 5 or somethingswaffelay
Does this help? stackoverflow.com/q/14290364. There are several other Q/As listed in stackoverflow alone: stackoverflow.com/search?q=%5Br%5D+%5Bggplot%5D+heatmap (I'm guessing googling for r ggplot2 heatmap might also be helpful to see various options.)r2evans

1 Answers

1
votes

Here's a sample given a small matrix.

First, I'll generate the matrix ... you use whatever data you want.

m <- matrix(1:25, nr=5)
m
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    6   11   16   21
# [2,]    2    7   12   17   22
# [3,]    3    8   13   18   23
# [4,]    4    9   14   19   24
# [5,]    5   10   15   20   25

Now, convert it to the "long" format that ggplot2 prefers:

library(dplyr)
library(tidyr)
longm <- cbind(m, x = seq_len(nrow(m))) %>%
  as.data.frame() %>%
  gather(y, val, -x) %>%
  mutate(y = as.integer(gsub("\\D", "", y)))
head(longm)
#   x y val
# 1 1 1   1
# 2 2 1   2
# 3 3 1   3
# 4 4 1   4
# 5 5 1   5
# 6 1 2   6

And a plot:

library(ggplot2)
ggplot(longm, aes(x, y, fill=val)) + geom_tile()
# or, depending on other factors, otherwise identical
ggplot(longm, aes(x, y)) + geom_tile(aes(fill=val))

sample ggplot heatmap

It's notable (to me) that the top-left value in the matrix (m[1,1]) is actually the bottom-left in the heatmap. This can be adjusted with scale_y_reverse(). From here, it should be primarily aesthetics.