If the column names of a data.frame
are started with numbers, or have spaces, aes_string()
fails to handle them:
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
Is there any way to have spaces in the column names, or they are started with numbers, and we can use them in ggplot2? Please consider we might don't know the column name, so please avoid to provide examples with constant column names - something like below:
aes_string(x=`1st Col`, y=`2nd Col`)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…