Ali Ali - 29 days ago 5
R Question

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

Answer

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