【问题标题】:Plotting a hex bin in R and ggplot2 using a continuous Z fill variable使用连续 Z 填充变量在 R 和 ggplot2 中绘制十六进制 bin
【发布时间】:2013-06-25 05:25:16
【问题描述】:

我的数据集包含三个变量:经度 (x)、纬度 (y) 和一个连续变量,为此我将其称为 z。

我正在尝试使用 hexbin 库中的 stat_binhex 函数通过 hex bin 来可视化 z 的总和,而不是 (x,y) 点的计数。我知道如果我将 z 强制为一个因子,那么对于小样本量有一个简单的解决方法,但显然这对于​​大的连续 z 既不可行也不可取。

library(ggplot2)
library(hexbin)

x <- runif(1000, -125, -65)
y <- runif(1000, 25, 50)
z <- runif(1000, 1, 30000000)
test <- data.frame(x=x, y=y, z=z)

p <- ggplot(test, aes(x=x, y=y, fill=z))

p <- p + stat_binhex(binwidth=c(.5,.5))

p

> Error in unit(tic_pos.c, "mm") : 'x' and 'units' must have length > 0

【问题讨论】:

    标签: r


    【解决方案1】:

    我认为解决方案在ggplot2 的手册中。你可能想要的功能是[stat_summary_hex][1]:

    library(ggplot2)
    library(hexbin)
    
    x <- runif(1000, -125, -65)
    y <- runif(1000, 25, 50)
    z <- runif(1000, 1, 30000000)
    test <- data.frame(x=x, 
                       y=y, 
                       z=z)
    
    p <- ggplot(data = test,
                aes(x = x,
                    y = y,
                    z = z)) +
      stat_summary_hex(fun = function(x) sum(x))
    
    print(p)
    

    你最终会得到这样的结果:

    【讨论】:

    • 请注意,您可以直接说 fun=sum 而不是将其写成匿名函数
    • 非常真实!我只是喜欢在做一个这样的例子时把它写出来。
    猜你喜欢
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多