Dr. Who
Dr. Who

Reputation: 141

How to plot points using hexagonal binning with user defined colors in ggplot2

I want to plot a "scatter plot" of X and Y using hexagonal binning. Currently, I have this code:

library(ggplot2)
X=rnorm(1000)
Y=rnorm(1000)
Z=sin(X)
df = data.frame(X,Y,Z)

p = ggplot(df, aes(X, Y)) + 
  stat_binhex()
plot(p)

The code produces a plot in which the color of each hexagon represents the number of points in the bin. I want the color to reflect the Z variable in my df (since the points are binned, the color reflect the mean of binned Z). How can I do this?

Upvotes: 2

Views: 354

Answers (1)

mt1022
mt1022

Reputation: 17289

I think you need stat_summary_hex and colors can be specified with scale_fill_continuous:

ggplot(df, aes(X, Y)) +
    stat_summary_hex(aes(z = Z)) +
    scale_fill_continuous(low = 'blue', high = 'red')

Upvotes: 2

Related Questions