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

后端 未结 2 607
一向
一向 2020-12-18 01:27

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 wan

2条回答
  •  轮回少年
    2020-12-18 01:55

    I accidentally answered your question writing a question of my own. I figured out that stat_bin2d will work when you convert the variable you are binning from number to text, so:

    library(ggplot2)
    data <- data.frame(x = rnorm(1000), y = rnorm(1000))
    x_t<-as.character(round(data$x,.1))
    y_t<-as.character(round(data$y,.1))
    x_x<-as.character(seq(-3,3),1)
    y_y<-as.character(seq(-3,3),1)
    data<-cbind(data,x_t,y_t)
    
    
    
    ggplot(data, aes(x = x_t, y = y_t)) +
      geom_bin2d() + 
      stat_bin2d(geom="text", aes(label=..count..))+
      scale_x_discrete(limits =x_x) +
      scale_y_discrete(limits=y_y) 
    

    So there you go. Unfortunately you have to set the binwidths outside of ggplot() so it isnt an ideal solution. I don't know why it works when you convert the variables to text, but there it is.

提交回复
热议问题