如果的列名data.frame
都开始使用数字或有空格, aes_string()
无法处理它们:
foo=data.frame("1st Col"=1:5, "2nd Col"=5:1, check.names=F)
bar=colnames(foo)
ggplot(foo, aes_string(x=bar[1],y=bar[2])) + geom_point()
# Error in parse(text = x) : <text>:1:2: unexpected symbol
# 1: 1st
# ^
foo=data.frame("First Col"=1:5, "Second Col"=5:1, check.names=F)
bar=colnames(foo)
ggplot(foo, aes_string(x=bar[1],y=bar[2])) + geom_point()
# Error in parse(text = x) : <text>:1:7: unexpected symbol
# 1: First Col
# ^
foo=data.frame("First_Col"=1:5, "Second_Col"=5:1, check.names=F)
bar=colnames(foo)
ggplot(foo, aes_string(x=bar[1],y=bar[2]))+geom_point()
# Now it works
有没有办法有在列名的空间,或者他们开始用数字,我们可以在GGPLOT2使用它们? 请考虑我们可能不知道列名,因此,应避免提供的例子具有恒定的列名 - 类似下面:
aes_string(x=`1st Col`, y=`2nd Col`)
据我所知,此方法应编程工作:
foo=data.frame("1st Col"=1:5, "2nd Col"=5:1, check.names=F)
#Save the colnames
bar=colnames(foo)
#change the names to something usable
names(foo) <- c("col1", "col2")
#Plot with arbitrary labs
ggplot(foo, aes(x=col1, y=col2)) + geom_point()+
labs(x=bar[1], y=bar[2])
原来的问题询问如何修改变量的值,因此是可以接受的ggplot()当值不事先知道。
编写一个函数,增加了背蜱开始和变量的值的结尾:
# ggName -> changes a string so it is enclosed in back-ticks.
# This can be used to make column names that have spaces (blanks)
# or non-letter characters acceptable to ggplot2.
# This version of the function is vectorized with sapply.
ggname <- function(x) {
if (class(x) != "character") {
return(x)
}
y <- sapply(x, function(s) {
if (!grepl("^`", s)) {
s <- paste("`", s, sep="", collapse="")
}
if (!grepl("`$", s)) {
s <- paste(s, "`", sep="", collapse="")
}
}
)
y
}
例子:
ggname(12)
[1] 12
ggname("awk ward")
“`AWK ward`”
l <- c("awk ward", "no way!")
ggname(l)
“`AWK ward`” “`没办法!'”
您可以使用该功能aes_string2
下方,而不是aes_string
:
aes_string2 <- function(...){
args <- lapply(list(...), function(x) sprintf("`%s`", x))
do.call(aes_string, args)
}
我有类似的情况,我用``使其明白:
mydf$ROIs <- row.names(mydf)
df.long <- melt(mydf)
colnames(df.long)[3] <- "Methods"
colnames(df.long)[4] <- "Mean L2 Norm Error"
variable.name="Variable", na.rm=TRUE)
ggplot(df.long, aes(ROIs, `Mean L2 Norm Error`, fill=Methods))+
geom_bar(stat="identity",position="dodge")+
theme(axis.text.x=element_text(angle=45,hjust=1,vjust=1))
文章来源: ggplot2 aes_string() fails to handle names starting with numbers or containing spaces