问题
I'm trying to do my first ever filled contour plot using ggplot
. With my data, I was specting something like:
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))
What I'm doing wrong, and where I can find more datailed information about this plots?
回答1:
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))
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))
来源:https://stackoverflow.com/questions/47620012/contour-plot-is-not-been-filled-completely-using-ggplot