Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contour plot is not been filled completely using ggplot

I'm trying to do my first ever filled contour plot using ggplot. With my data, I was specting something like:

enter image description here

But my result was:

a <- c(1, 1.1, 1, 1.3, 1.2, 2, 2.2, 2, 2.5, 2.1, 3, 3, 3, 3.1, 3.2)
b <- c(rep(c(0, 5, 10, 15, 20), 3))
c <- seq(0, 1000, by = 1000/14)

DF <- data.frame(a, b, c)

ggplot(DF, aes(x = a, y = b, z = c)) +
  geom_raster(aes(fill = c)) +
  geom_contour() + scale_fill_gradientn(colours = rainbow(10))

enter image description here

What I'm doing wrong, and where I can find more datailed information about this plots?

like image 599
Daniel Valencia C. Avatar asked Jul 13 '26 04:07

Daniel Valencia C.


1 Answers

Here is an example:

generate coordinates:

b = c(0, 5, 10, 15, 20)
a = (1:30)/10

generate all combinations of coordinates

df <- expand.grid(a, b)

generate c via tcrossprod of a and b+1 (this is completely arbitrary but will generate a nice pattern)

df$c <- as.vector(a %o% (b+1))

ggplot(df, aes(x = Var1, y = Var2, z = c, fill = c)) +
  geom_raster(interpolate = T) + #interpolate for success 
  scale_fill_gradientn(colours = rainbow(10))

enter image description here

generally if you have a matrix of values (z values) to be plotted in ggplot you will need to convert it to long format via melt in reshape2 or gather in tidyr and then use for plotting.

Your data is very sparse, one approach to overcome this is to generate the missing data. I will show how to accomplish with loess function:

model <- loess(c ~ a + b, data = DF) #make a loess model based on the data provided (data in OP)

z <- predict(model, newdata = expand.grid(a = (10:30)/10, b = (0:200)/10)) #predict on the grid data

df <- data.frame(expand.grid(a = (10:30)/10, b = (0:200)/10), c = as.vector(z)) #append z to grid data

ggplot(df, aes(x = a, y = b, z = c, fill = c)) +
  geom_raster(interpolate = T)+
  scale_fill_gradientn(colours = rainbow(10))

enter image description here

like image 146
missuse Avatar answered Jul 15 '26 18:07

missuse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!