我正在尝试使用 ggplot2 绘制一个直方图,该直方图对于不同的 x 间隔具有不同的颜色条。
引用 Hadley 的解决方案后:how to define fill colours in ggplot histogram? ,我得出以下结果:
library(ggplot2)
set.seed(1)
a <- seq(from=1, to=10000)
b <- rnorm(10000)
c <- data.frame(a,b) # Convert to DF
ggplot(c, aes(x=b, fill=cut(..x.., breaks=c(-2, -1, -0.5, 0, 0.5, 1, 2)))) +
geom_histogram(binwidth=0.1, color="steelblue")
但是,当我尝试将断点定义到要传递到 aes() 的变量 MyBreaks 中时,我收到错误消息:“Error in cut.default(x, breaks = MyBreaks) : object 'MyBreaks'没有找到。”
我产生错误的代码:
MyBreaks <- c(-2, -1, -0.5, 0, 0.5, 1, 2)
ggplot(c, aes(x=b, fill=cut(..x.., breaks=MyBreaks))) +
geom_histogram(binwidth=0.1, color="steelblue")
我对其他用户遇到的类似错误进行了一些研究,但这些解决方案似乎对我不起作用。
例如How to use earlier declared variables within aes in ggplot with special operators (..count.., etc.)中的解决方案给了:“错误:美学必须是长度一,或者与 dataProblems:MyBreaks 的长度相同”。我的代码是:
ggplot(c, aes(x=b, MyBreaks1=MyBreaks, fill=cut(..x.., breaks=MyBreaks1))) +
geom_histogram(binwidth=0.1, color="steelblue")
然后我尝试了 Local Variables Within aes 中的解决方案但这给出了相同的:“cut.default(x, breaks = MyBreaks) 中的错误:未找到对象‘MyBreaks’”。我的代码是:
.e <- environment()
ggplot(c, aes(x=b, fill=cut(..x.., breaks=MyBreaks)), environment = .e) +
geom_histogram(binwidth=0.1, color="steelblue")
我以前做过基础编程,但 R 的学习曲线真的很陡峭!如果有人可以提供帮助,我们将不胜感激!
提前致谢!
最佳答案
这是来自 Roland 的评论 How to use earlier declared variables within aes in ggplot with special operators (..count.., etc.) .
ggplot(c, aes(x=b, fill=cut(..x.., breaks=get("MyBreaks", envir=.GlobalEnv)))) +
geom_histogram(binwidth=0.1, color="steelblue")
关于r - 将变量传递给 ggplot2 的 aes() 中的 cut(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20746121/