0
votes

I have a dataframe with two variables plotted along the x- and y-axis, as a simple scatter plot, and I would like to add a third variable, but instead of getting the z-axis, I want to represent the points density of said z variable as a background for the scatterplot. I would look like this, taken from the litterature:

enter image description here

Data would not matter as I would work with the general method for such a plot, but you can use something like this:

df<-data.frame(IDOBS=c(1:1000),var1=runif(1000,0,30),var2=runif(1000,1500,3000),var3=runif(1000,0.5,1.5))

So with var1 and var2 as x and y variables respectively, and the background depending on var3.

Thank you in advance for your help,

C.

1
You can color the individual points based on the var3 value, but to create a background color as you asked you need a surface. You first need to decide how will the var3 be converted into a surface. - Rohit Das

1 Answers

0
votes

So apparently I've been missing the name of such a plot, which is a contour plot or level plot. A simple function in lattice allows you to do it. I've used the following code, found on this R blog:

df<-data.frame(x=runif(1000,670,3300),y=runif(1000,2,30),z=runif(1000,0.5,1.5))

gni.loess = loess(z ~ x*y, data = df, degree = 2, span = 0.25)

gni.fit = expand.grid(list(x = seq(670, 3300, 0.1), y = seq(2, 30, 0.1)))

z = predict(gni.loess, newdata = gni.fit)
gni.fit$prod=as.numeric(z)

levelplot(prod ~ x*y, data = gni.fit,
          xlab = "x", ylab = "y",
          main = "z on an x*y grid",
          col.regions = terrain.colors(100)
)

Which gives something like this (random since there is no relation between [x,y] and z in the example):

I am still trying to add the scatterplot of y~x on top of it though.

EDIT: solution with ggplot2 is easier to use for multilayer plots, but gives less defined boundaries for the level plot (i.e. more continuous color spectrum for the values of z on the plot). Adding the original (x,y) scatterplot (as opposed to the transformed values obtained with expand.grid) is possible via geom_point() for example. Another possibility, less appealing graphically but a lot simpler, is to use a geom_point() expression such as this:

p<-ggplot(df,aes(x,y))
p + geom_point(data=df, aes(x,y, color=z))+ scale_colour_gradient(low = "green", high="red")

Giving:

enter image description here