如何使用特殊运算符(..count.. 等)在 ggplot 中的 aes 中使用较早声明的变量 [英] How to use earlier declared variables within aes in ggplot with special operators (..count.., etc.)

查看:19
本文介绍了如何使用特殊运算符(..count.. 等)在 ggplot 中的 aes 中使用较早声明的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想用以下公式绘制直方图(我知道这不是最好的,但它可以说明问题):

Let's say I want to plot histogram with the following formula (I know it's not the best but it will illustrate the problem):

set.seed(1)
dframe <- data.frame(val=rnorm(50))
p <- ggplot(dframe, aes(x=val, y=..count..))
p + geom_bar()

它工作得很好.但是,假设我们出于某种原因想要将频率除以早期定义的数字.我的镜头是:

It works just fine. However let's say that we want for some reason frequencies divided by an earler defined number. My shot would be:

k <- 5
p <- ggplot(dframe, aes(x=val, y=..count../k))
p + geom_bar()

但是我遇到了这个烦人的错误:

However I get this annoying error:

Error in eval(expr, envir, enclos) : object 'k' not found

是否存在一种将 ..count.. 类变量与一些预定义变量一起使用的方法?

Does there exist a way for using both ..count..-like variables with some predefined ones?

推荐答案

当你使用一些 stat 进行绘图时,ggplot() 函数似乎存在一些错误(例如 y=..count..).函数 ggplot() 已经有 environment 变量,因此它可以使用在此函数之外定义的变量.

It seems that there is some bug with ggplot() function when you use some stat for plotting (for example y=..count..). Function ggplot() has already environment variable and so it can use variable defined outside this function.

例如这会起作用,因为 k 仅用于更改 x 变量:

For example this will work because k is used only to change x variable:

k<-5
ggplot(dframe,aes(val/k,y=..count..))+geom_bar()

这会产生错误,因为 k 用于更改使用 stat y=..count.. 计算的 y >

This will give an error because k is used to change y that is calculated with stat y=..count..

k<-5
ggplot(dframe,aes(val,y=..count../k))+geom_bar()
Error in eval(expr, envir, enclos) : object 'k' not found

要解决这个问题,你可以在 aes() 中 kefine k.

To solve this problem you can kefine k inside the aes().

k <- 5
ggplot(dframe,aes(val,k=k,y=..count../k))+geom_bar()

这篇关于如何使用特殊运算符(..count.. 等)在 ggplot 中的 aes 中使用较早声明的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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