ggplot aes_string不适用于空格 [英] ggplot aes_string doesn't work with spaces

查看:71
本文介绍了ggplot aes_string不适用于空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不起作用:

mydat <- data.frame(`Col 1`=1:5, `Col 2`=1:5, check.names=F)
xcol <- "Col 1"
ycol <- "Col 2"
ggplot(data=mydat, aes_string(x=xcol, y=ycol)) + geom_point()

作品:

mydat <- data.frame(`A`=1:5, `B`=1:5)
xcol <- "A"
ycol <- "B"
ggplot(data=mydat, aes_string(x=xcol, y=ycol)) + geom_point()

工作.

mydat <- data.frame(`Col 1`=1:5, `Col 2`=1:5, check.names=F)
ggplot(data=mydat, aes(x=`Col 1`, y=`Col 2`)) + geom_point()

出什么问题了?

推荐答案

传递给aes_string的值是parse() -d.这是因为您可以传递aes_string(x="log(price)")之类的内容,而不传递一个列名,而是一个表达式.因此,它会将您的字符串当作一个表达式对待,并且在解析它时,它会找到空格,这是一个无效的表达式.您可以通过将列名称括在引号中来解决"此问题.例如,这有效

Values passed to aes_string are parse()-d. This is because you can pass things like aes_string(x="log(price)") where you aren't passing a column name but an expression. So it treats your string like an expression and when it goes to parse it, it finds the space and that's an invalid expression. You can "fix" this by wrapping column names in quotes. For example, this works

mydat <- data.frame(`Col 1`=1:5, `Col 2`=1:5, check.names=F)
xcol <- "Col 1"
ycol <- "Col 2"
ggplot(data=mydat, aes_string(x=shQuote(xcol), y=shQuote(ycol))) + geom_point()

我们只是使用shQuote()来将值括在双引号中.您还可以像在其他示例中一样在字符串中嵌入单个刻度线

We just use shQuote() to but double quotes around our values. You could have also embedded the single ticks like you did in the other example in your string

mydat <- data.frame(`Col 1`=1:5, `Col 2`=1:5, check.names=F)
xcol <- "`Col 1`"
ycol <- "`Col 2`"
ggplot(data=mydat, aes_string(x=xcol, y=ycol)) + geom_point()

但是,解决此问题的最佳方法是不使用不是有效变量名的列名.

But the real best way to deal with this is to not use column names that are not valid variable names.

这篇关于ggplot aes_string不适用于空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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