4

I really like the idea of a hexbin density plot in ggplot, and I try to use it (instead of a square-shaped bin as produced by stat_bin2d) whenever I can. However, the boundries of the hexagons are sometimes obvious. For example,

d <- ggplot(diamonds, aes(carat, price))

d + stat_binhex()

enter image description here

In this picture the boundaries of hexagons show up as little white lines, which sometimes interferes with my attempt to conceive the true "density" variations in the picture.

If I use stat_bin2d, the boundaries lines are not shown at all :

d <- ggplot(diamonds, aes(carat, price))

d + stat_bin2d()

enter image description here

So my questions are:

  1. Why the hexagon boundaries are displayed while square boundaries aren't.

  2. More importantly, is there a way to do stat_hexbin without showing boundary lines?

Thanks very much!

Aside: I prefer to do hexagon density plot in ggplot rather than using some other package mainly because I like the flexibility of adding other layers to it later on.

Ying Zhang
  • 171
  • 6
  • Possible workaround: you could just change the color of the outline to match the color of hexagons themselves, something like `stat_binhex(color = 'royalblue4')` – ytk Jan 10 '16 at 01:00
  • Thanks Teja. It sounds plausible, but when I tried it the pic doesn't look very satisfactory... – Ying Zhang Jan 11 '16 at 18:32

1 Answers1

6

Using the link to ggplot2 multiple stat_binhex() plots with different color gradients in one image as a reference I was able to do what you are asking with the following code:

d <- ggplot(diamonds, aes(carat, price))
d + stat_binhex(aes(colour = ..count..))

or

d <- ggplot(diamonds, aes(carat, price, colour = ..count..))
d + stat_binhex()

enter image description here

Community
  • 1
  • 1
steveb
  • 5,382
  • 2
  • 27
  • 36
  • 1
    Thanks. Now I understand in stat_binhex(aes(colour = ..., fill = ...)), colour controls cloring the boundary, fill controls coloring the inside of each hexagon. Although I didn't say in the original question, in my real problem I wanted to add other layers in the picture, where I need to use scale_color_manual to provide colors for a few discrete colors. For example, on top of the blue-ish density plot, I want to plot a few outlier points in red. That gives me a problem because I have to choose either a discrete or a continuous color scale in one plot, but not both – Ying Zhang Jan 11 '16 at 18:29
  • on "choose either a discrete or a continuous color scale in one plot, but not both": http://stackoverflow.com/questions/11508902/plotting-discrete-and-continuous-scales-in-same-ggplot – Ying Zhang Jan 11 '16 at 18:31