在 ggplot2 中是否有内置的对数色标的方法? [英] Is there a built-in way to do a logarithmic color scale in ggplot2?

查看:21
本文介绍了在 ggplot2 中是否有内置的对数色标的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个分箱密度图的例子:

Here's an example of a binned density plot:

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

调整色阶会很好,以便中断是对数间隔的,但是试试

It would be nice to adjust the color scale so that the breaks are log-spaced, but a try

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

导致 错误:提供给离散 scale_hue 的连续变量 (). 似乎中断是期望一​​个因子(也许?)并在设计时考虑了分类变量?

Results in an Error: Continuous variable () supplied to discrete scale_hue. It seems breaks is expecting a factor (maybe?) and designed with categorical variables in mind?

我将发布一个非内置的解决方法作为答案,但我想我可能只是在使用 scale_fill_hue 时迷失了方向,我想知道是否有任何明显我遗漏的东西.

There's a not built-in work-around I'll post as an answer, but I think I might just be lost in my use of scale_fill_hue, and I'd like to know if there's anything obvious I'm missing.

推荐答案

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

Yes! There is a trans argument to scale_fill_gradient, which I had missed before. With that we can get a solution with appropriate legend and color scale, and nice concise syntax. Using p from the question and my_breaks = c(2, 10, 50, 250, 1250, 6000):

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

我的另一个答案最适合用于更复杂的数据功能.Hadley 的评论鼓励我在 ?scale_gradient 底部的示例中找到这个答案.

My other answer is best used for more complicated functions of the data. Hadley's comment encouraged me to find this answer in the examples at the bottom of ?scale_gradient.

这篇关于在 ggplot2 中是否有内置的对数色标的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆