ggplot aes_string 不适用于空格

thc*_*thc 6 r ggplot2

不起作用:

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()
Run Code Online (Sandbox Code Playgroud)

作品:

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

作品。

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()
Run Code Online (Sandbox Code Playgroud)

有什么问题?

MrF*_*ick 6

价值传递给aes_stringparse()-d。这是因为您可以传递诸如aes_string(x="log(price)")不传递列名而是传递表达式之类的东西。所以它把你的字符串当作一个表达式,当它解析它时,它找到了空格,这是一个无效的表达式。您可以通过将列名称括在引号中来“修复”此问题。例如,这有效

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()
Run Code Online (Sandbox Code Playgroud)

我们只是shQuote()在我们的价值观周围使用双引号。您也可以像在字符串中的另一个示例中那样嵌入单个刻度

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()
Run Code Online (Sandbox Code Playgroud)

但是处理这个问题的真正最好的方法是不要使用不是有效变量名的列名。