Reputation: 4406
I am trying to draw contour plot with ggplot2 and it is proving to be a little harder than I imagined. Using the iris
dataset I am able to produce this plot:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
stat_density2d(geom="polygon", aes(fill=..level..))
My issue is that I can't seem to figure out how to display- rather than the density values -the raw Sepal.Width
values. Here is what I've tried:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, z=Sepal.Width)) +
geom_tile(aes(fill=Sepal.Width))+
stat_contour(aes(colour=..level..))
This produces an especially odd error message:
Warning message:
Computation failed in `stat_contour()`:
(list) object cannot be coerced to type 'double'
I also tried this:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
stat_density2d(geom="polygon", aes(fill=Sepal.Width))
And lastly this:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
geom_tile()
Can anyone recommend a good way to produce a contour plot in ggplot2 with the values of the variable itself producing the levels of the contour?
UPDATED
From the stat_contour
example:
# Generate data
library(reshape2) # for melt
volcano3d <- melt(volcano)
names(volcano3d) <- c("x", "y", "z")
# Basic plot
ggplot(volcano3d, aes(x, y, z = z)) +
stat_contour(geom="polygon", aes(fill=..level..))
Work great and looks great. But if I apply this exactly to the iris example like so:
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
stat_contour(geom="polygon", aes(fill=..level..))
I get this error message:
Warning message:
Computation failed in `stat_contour()`:
(list) object cannot be coerced to type 'double'
These are both dataframes with similar structure so I can't figure out what is different between the two causing this issue.
Upvotes: 9
Views: 4658
Reputation: 4406
The ultimate solution to this way to use the akima
package for interpolation then the ggplot2
for final plotting. This is the method I used:
library(ggplot2)
library(akima)
library(dplyr)
interpdf <-interp2xyz(interp(x=iris$Petal.Width, y=iris$Petal.Length, z=iris$Sepal.Width, duplicate="mean"), data.frame=TRUE)
interpdf %>%
filter(!is.na(z)) %>%
tbl_df() %>%
ggplot(aes(x = x, y = y, z = z, fill = z)) +
geom_tile() +
geom_contour(color = "white", alpha = 0.05) +
scale_fill_distiller(palette="Spectral", na.value="white") +
theme_bw()
Upvotes: 5
Reputation: 24198
Try factorizing the fill
in stat_density2d()
ggplot(iris, aes(x=Petal.Width, y=Petal.Length, fill=Sepal.Width)) +
stat_density2d(geom="polygon", aes(fill = factor(..level..)))
Upvotes: 2