Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

r - How to use stat_bin2d() to compute counts labels in ggplot2?

I wish to build a plot, essentially identical to that which i can produce using ggplots 'stat_bin2d' layer, however instead of the counts being mapped to a variable, I want the counts associated with the bin to be displayed as a label to each bin.

I got the following solution to the equivalent 1D problem from another thread

data <- data.frame(x = rnorm(1000), y = rnorm(1000))

ggplot(data, aes(x = x)) +
  stat_bin() +  
  stat_bin(geom="text", aes(label=..count..), vjust=-1.5)

The counts for each bin are clearly labeled. However moving from the 1D to 2D case, this works,

ggplot(data, aes(x = x, y = y)) +
  stat_bin2d()

But this returns an error.

ggplot(data, aes(x = x, y = y)) +
  stat_bin2d() +  
  stat_bin2d(geom="text", aes(label=..count..))

Error: geom_text requires the following missing aesthetics: x, y
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In more recent versions of ggplot this is perfectly possible and works without errors.

Just be sure that you use the same arguments to both call of stat_bin2d(). For example, set binwidth = 1 on both lines:

library(ggplot2)
data <- data.frame(x = rnorm(1000), y = rnorm(1000))

ggplot(data, aes(x = x, y = y)) +

  geom_bin2d(binwidth = 1) + 
  stat_bin2d(geom = "text", aes(label = ..count..), binwidth = 1) +
  scale_fill_gradient(low = "white", high = "red") +
  xlim(-4, 4) +
  ylim(-4, 4) +
  coord_equal()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...