1

I want to plot a function graph with R. The target function is z = 4*x^2 + lambda *y^2.

Given that z = c(0,2,4,6) and lambda = c(4, 2, 1, 0, -1, -2, -4).

I want to plot it in a contour map form.

The below is my code:

library(ggplot2)
rm(list=ls())
lambda = c(4, 2,1,0,-1,-2,-4)
plane = c(0,2,4,6)
x = seq(-5,5,length.out=100)
y = seq(-5,5,length.out=100)
i = 1
t = transform(expand.grid(x = x, y=y), z=4*x^2+lambda[i]*y^2)
dat = data.frame(t,"category"=c(rep(i,length(t$x))))
for(i in 2:7){
  t = transform(expand.grid(x = x, y=y), z=4*x^2+lambda[i]*y^2)
  dat = rbind(dat, 
  data.frame(t,"category"=c(rep(i,length(t$x)))))
  }
  ggplot(data = dat, aes(x = x, y=y, z=z, color = category))+
  stat_contour(breaks = plane)

But I failed to plot the graph QQ...

Ken Hsu
  • 421
  • 3
  • 9
  • As your code produces warning `"stat_contour(): Zero contours were generated"`, see related post: https://stackoverflow.com/q/19065290/680068 – zx8754 Jan 10 '22 at 09:36
  • Could you explain briefly what's the role of `z`. Usually, given that you have f(x,y)=z, some would expect that you have x and y (and different lambdas) and you are calculating the response of the function, which is z. So, why do you have only 4 pre-defined entries in z? – JKupzig Jan 10 '22 at 11:44
  • I want to limit the z shown on the graph. – Ken Hsu Jan 10 '22 at 12:47
  • I rewrote the code as @zx8754 said, but now I cannot plot them from different categories. – Ken Hsu Jan 10 '22 at 12:55
  • 1
    Did you try to transfrom the categories into factors, e.g. `dat$category <- as.factor(dat$category)`? – JKupzig Jan 10 '22 at 13:24
  • I miss a bit on what you want as a final result, you want to color the categories but how are you going to cope with the levels / depth (z-values)? – Merijn van Tilborg Jan 10 '22 at 15:10
  • It seems to be a problem....I plotted each function with different lambdas in separate graphs...thanks for everyone's opinion!!!!!! – Ken Hsu Jan 31 '22 at 09:13

0 Answers0