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

后端 未结 2 594
一向
一向 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.

    0 讨论(0)
  • 2020-12-18 02:07

    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()
    

    0 讨论(0)
提交回复
热议问题