r - 将变量传递给 ggplot2 的 aes() 中的 cut()

标签 r ggplot2 cut

我正在尝试使用 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/

相关文章:

r - 在 R 中分割字符串时有效替换 for 循环

r - 使用条件语句更改数据点的颜色

r - 如何根据每个元素中有多少个字符来拆分 R 中的列?

r - 找不到 geom_rect() 主变量

r - 使用 ggplot2 绘制按时间顺序排列的时间线

sed - 使用带特殊字符的 sed

r - text2vec 和 topicmodels 是否可以通过适合 LDA 的参数设置来生成类似的主题?

r - 在内存中创建 ggplot2 图?

python - 如果这个 python 脚本在 linux 上,我怎样才能得到一个值?

bash - xargs 并剪切 : getting `cut` fields of a csv to bash variable