是否有内置的方法在ggplot2中进行对数色标?

时间:2011-11-09 18:38:51

标签: r ggplot2

以下是分箱密度图的示例:

require(ggplot2)
n <- 1e5
df <- data.frame(x = rexp(n), y = rexp(n))
p <- ggplot(df, aes(x = x, y = y)) + stat_binhex()
print(p)

enter image description here

调整色阶以便断点是间隔的,但尝试

会很不错
my_breaks <- round_any(exp(seq(log(10), log(5000), length = 5)), 10)
p + scale_fill_hue(breaks = as.factor(my_breaks), labels = as.character(my_breaks))

Error: Continuous variable () supplied to discrete scale_hue.结果似乎中断是期待一个因素(可能是?)并且设计时考虑了分类变量?

有一个没有内置的解决方法,我会发布作为答案,但我想我可能只是在使用scale_fill_hue时迷失了,我想知道是否有任何明显的我我失踪了。

2 个答案:

答案 0 :(得分:97)

是的! transscale_fill_gradient个参数,我之前错过了。{1}}。有了这个,我们可以得到一个具有适当的图例和色标,以及简洁的语法的解决方案。使用问题中的pmy_breaks = c(2, 10, 50, 250, 1250, 6000)

p + scale_fill_gradient(name = "count", trans = "log",
                        breaks = my_breaks, labels = my_breaks)

enter image description here

我的其他答案最适合用于更复杂的数据功能。哈德利的评论鼓励我在?scale_gradient底部的例子中找到这个答案。

答案 1 :(得分:18)

另一种方法,使用stat_summary_hex中的自定义函数:

ggplot(cbind(df, z = 1), aes(x = x, y = y, z = z)) + 
  stat_summary_hex(function(z){log(sum(z))})

这是ggplot的一部分,但最初的灵感来自@kohske在this answer中的精彩代码,它提供了自定义stat_aggrhex。在ggplot&gt;的版本中2.0,使用上面的代码(或其他答案)

ggplot(cbind(df, z = 1), aes(x = x, y = y, z = z)) +
    stat_aggrhex(fun = function(z) log(sum(z))) +
    labs(fill = "Log counts")

生成此图。

enter image description here