在ggplot2中是否有内置的方法来实现对数色阶? [英] Is there a built-in way to do a logarithmic color scale in 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)
调整颜色比例以使间隔为对数间距,但试一试
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的连续变量()。
看起来break是期待一个因素(也许是?分类变量?
有一个没有内置的解决办法,我会作为答案张贴,但我想我可能只是在使用 SC ale_fill_hue
,我想知道是否有任何明显的我缺少。
scale_fill_gradient
有一个 trans
参数,这是我以前错过的。有了这个,我们可以得到一个具有适当的图例和颜色比例以及简洁的语法的解决方案。从问题中使用 p
,并使用 my_breaks = c(2,10,50,250,1250,6000)
: p + scale_fill_gradient(name =count,trans =log,
breaks = my_breaks,labels = my_breaks )
?scale_gradient 底部的例子中找到这个答案。
Here's an example of a binned density plot:
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)
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))
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?
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.
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)
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屋!