ggplot中的反引号和引号中的引号之间的区别

时间:2015-11-07 00:06:02

标签: r ggplot2

好的,这有点奇怪。我正在为geom_histogram的初学者回答一个问题,并且OP发布了一个使用反引号的示例。他忽略了添加数据,所以我做了,然后找到了答案,甚至没有注意到反引号。但另一个(实际上更优雅)的答案是在没有反引号的情况下发布的。它并没有真正起作用,但它在反引号方面效果更好。

但现在我很困惑。我不明白为什么应该有所不同。即使ggplot列表几乎相同,只有ggplot$mapping元素是不同的,我可以看到(好吧,这是一个大问题)。我用谷歌搜索过,但我不知道发生了什么。

所以这是代码:

Log Numberaes周围的引号):

#Generate some data
lon <- log(rnorm(1000, exp(6)))
state <- sample(c("c", "l", "t"), 1000, replace = T)
d <- data.frame(lon, state)
names(d) <- c("Log Number", "state")

# Plot it
gpsq <- ggplot(d, aes(x = 'Log Number', fill = state)) + geom_histogram()
print(gpsq)

产生

enter image description here

但是这个Log Numberaes周围的反复记录):

#Generate some data
lon <- log(rnorm(1000, exp(6)))
state <- sample(c("c", "l", "t"), 1000, replace = T)
d <- data.frame(lon, state)
names(d) <- c("Log Number", "state")

# Plot it
gpsq <- ggplot(d, aes(x = `Log Number`, fill = state)) + geom_histogram()
print(gpsq)

更正确地得出这个:

enter image description here

1 个答案:

答案 0 :(得分:11)

返回刻度是在R中表示非标准变量名称的标准方式。引号用于表示字符串。例如:

`bad name` = 1
`bad name`
# [1] 1

这不适用于引号。

"bad name" = 1
"bad name"
# [1] "bad name"

通常,您不应该使用这些奇怪的非标准名称。但是,如果你必须这样做,那就是做到这一点的方法。你可以做很多事情,

`really-bad^name+violating*all()/[kinds] <- of == rules&!|` = 1
# works just fine

但这并不意味着

说到ggplot,如果你做了

ggplot(mtcars, aes(x = wt, y = 1)) + geom_point()

你会期望所有的y值都是1.而且你是对的!

使用带引号的字符串,它只是一样:

ggplot(mtcars, aes(x = wt, y = "mpg")) + geom_point()

除了代替上面y = 1案例中的数字之外,你给它一个字符 - 它被隐式转换为一个因子(只有一个级别),用于离散的y尺度(仅限于一个值)。如果有一个名为"mpg"的列,则无关紧要,因为您刚刚传递了aes()一个值。 ggplot并未查找名为mpg的列,就像它在第一个示例中没有查找名为1的列一样。

使用后退标记,您可以将ggplot R识别为对象名称,而不仅仅是1"some string"这样的值。因此ggplot 去寻找具有该名称的列。

# both of these work
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
ggplot(mtcars, aes(x = wt, y = `mpg`)) + geom_point()

虽然返回标记可以正常工作,但在aes()中设置常量通常可行,但这些都不是非常推荐的。设置常量的首选方法是将常量设置在aes() 之外。这是保证一切都能在更复杂的情节中很好地工作的唯一方法。特别是,如果你试图在aes()里面做奇怪的事情(尤其是转换),那么Facets通常会有错误或者不会产生预期的结果。

# better than above, set a constant outside of `aes()`
# Here I set y as a constant which is a bit unusual
ggplot(mtcars, aes(x = wt)) + geom_point(y = 1)
# aesthetics that are more commonly set to constants are
# size, color, fill, etc.

对于非标准列名称,aes_string()效果很好,然后希望美学映射为引用列名。如果您正在编写一个创建ggplots并需要将列名作为参数的函数,这也是一种很好的方法。

ggplot(mtcars, aes_string(x = "wt", y = "mpg")) + geom_point()
# or, in a variable
my_y_column = "mpg"
ggplot(mtcars, aes_string(x = "wt", y = my_y_column)) + geom_point()

另一个很好的例子,由于@TheTime:

,开始看起来很糟糕

最终,ggplot需要评估所有内容,这将通过eval完成。请考虑以下事项:

a <- 1

eval(parse(text="a"))
# [1] 1

eval(parse(text='"a"'))
# [1] "a"

eval(parse(text="`a`"))
# [1] 1