make ggplot2:: stat_bin2d show density instead of

2019-05-19 05:49发布

问题:

Is it possible to make it show within-group densities instead of counts?

library(ggplot2);data(diamonds)
ggplot(diamonds, aes(carat, depth)) +  
  stat_bin2d(bins=40)+ facet_wrap(~color)

This would make it easier to compare patterns among the groups, as some groups may naturally be more occurring.

The question is slightly similar to: How to scale (normalise) values of ggplot2 stat_bin2d within each column (by X axis) which is also lacking an answer.

回答1:

ggplot(diamonds, aes(carat, depth)) +  
  stat_bin2d(bins=40, aes(fill = ..density..))+ facet_wrap(~color)

Or would you be happy with a kernel density estimate?

ggplot(diamonds, aes(carat, depth)) +  
  stat_density2d(aes(fill = ..density..), geom = "tile", contour = FALSE, n = 25) + 
  facet_wrap(~color) +
  scale_fill_gradient(low = "light blue", high = "dark red")

Or with default grid:

ggplot(diamonds, aes(carat, depth)) +  
  stat_density2d(aes(fill = ..density..), geom = "tile", contour = FALSE) + 
  facet_wrap(~color) +
  scale_fill_gradient(low = "light blue", high = "dark red")



标签: r ggplot2