Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

r - ggplot2 aes_string() fails to handle names starting with numbers or containing spaces

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

enter image description here

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As far as I can tell, this method should work programmatically:

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])

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...