Contour levels corresponding to variable levels in ggplot2

人盡茶涼 提交于 2019-12-22 04:07:04

问题


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.


回答1:


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()




回答2:


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..)))



来源:https://stackoverflow.com/questions/35593967/contour-levels-corresponding-to-variable-levels-in-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!